├── NOTICE
├── .github
└── workflows
│ ├── scripts
│ ├── README.md
│ └── mailchimp
│ │ ├── package.json
│ │ ├── index.js
│ │ └── htmlContent.js
│ ├── update-maintainers-trigger.yaml
│ ├── automerge-for-humans-remove-ready-to-merge-label-on-edit.yml
│ ├── autoupdate.yml
│ ├── bump.yml
│ ├── automerge.yml
│ ├── please-take-a-look-command.yml
│ ├── transfer-issue.yml
│ ├── lint-pr-title.yml
│ ├── stale-issues-prs.yml
│ ├── automerge-orphans.yml
│ ├── add-good-first-issue-labels.yml
│ ├── if-nodejs-version-bump.yml
│ ├── if-nodejs-pr-testing.yml
│ ├── help-command.yml
│ ├── issues-prs-notifications.yml
│ ├── automerge-for-humans-merging.yml
│ ├── welcome-first-time-contrib.yml
│ ├── update-pr.yml
│ ├── bounty-program-commands.yml
│ ├── if-nodejs-release.yml
│ ├── release-announcements.yml
│ ├── automerge-for-humans-add-ready-to-merge-or-do-not-merge-label.yml
│ └── notify-tsc-members-mention.yml
├── .gitignore
├── components
├── Consumers.js
├── templates
│ ├── channelpool.interface.js
│ ├── amqpservice.interface.js
│ ├── channelpool.js
│ └── amqpservice.js
├── Publishers.js
└── Worker.js
├── template
├── src
│ ├── Services
│ │ ├── amqpservice.js
│ │ ├── channelpool.js
│ │ └── Interfaces
│ │ │ ├── iamqpservice.js
│ │ │ └── ichannelpool.js
│ ├── worker.js
│ ├── docker.js
│ ├── project.js
│ ├── Models
│ │ └── model.js
│ ├── program.js
│ ├── startup.js
│ └── appconfig.js
└── readme.js
├── CHANGELOG.md
├── CODEOWNERS
├── ISSUE_TEMPLATE.md
├── .allcontributorsrc
├── PULL_REQUEST_TEMPLATE.md
├── example
├── publisher.yaml
├── subscriber.yaml
└── asyncapi.yaml
├── test
├── consumers.test.spec.js
├── iamqpservice.test.spec.js
├── producers.test.spec.js
├── amqpservice.test.spec.js
└── common.test.spec.js
├── .eslintrc
├── README.md
├── package.json
├── CONTRIBUTING.md
├── CODE_OF_CONDUCT.md
├── utils
└── common.js
└── LICENSE
/NOTICE:
--------------------------------------------------------------------------------
1 | Copyright 2016-2025 AsyncAPI Initiative
2 |
3 | This product includes software developed at
4 | AsyncAPI Initiative (http://www.asyncapi.com/).
--------------------------------------------------------------------------------
/.github/workflows/scripts/README.md:
--------------------------------------------------------------------------------
1 | The entire `scripts` directory is centrally managed in [.github](https://github.com/asyncapi/.github/) repository. Any changes in this folder should be done in central repository.
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | coverage
2 | node_modules
3 | docs
4 | output
5 | .DS_Store
6 | __transpiled
7 | test/temp
8 | package-lock.json
9 | template/build
10 | template/composer.lock
11 | template/vendor
12 | template/phpcs.xml
13 | template/.phpunit.result.cache
14 | .env
15 | template/.env
16 | .idea/
17 |
--------------------------------------------------------------------------------
/components/Consumers.js:
--------------------------------------------------------------------------------
1 | export function Consumers({ channels }) {
2 | if (channels.length === 0) {
3 | return null;
4 | }
5 |
6 | return `
7 | // Code for the subscriber: Recieves messages from RabbitMq
8 | _amqpService.${channels[0].subscriber.operationId}();
9 | `;
10 | }
11 |
--------------------------------------------------------------------------------
/.github/workflows/scripts/mailchimp/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "schedule-email",
3 | "description": "This code is responsible for scheduling an email campaign. This file is centrally managed in https://github.com/asyncapi/.github/",
4 | "license": "Apache 2.0",
5 | "dependencies": {
6 | "@actions/core": "1.6.0",
7 | "@mailchimp/mailchimp_marketing": "3.0.74"
8 | }
9 | }
--------------------------------------------------------------------------------
/template/src/Services/amqpservice.js:
--------------------------------------------------------------------------------
1 | import { File, render } from '@asyncapi/generator-react-sdk';
2 | import { AmqpService } from '../../../components/templates/amqpservice';
3 |
4 | export default function ({ asyncapi, params }) {
5 | return (
6 |
7 | {render()}
8 |
9 | );
10 | }
11 |
--------------------------------------------------------------------------------
/template/src/Services/channelpool.js:
--------------------------------------------------------------------------------
1 | import { File, render } from '@asyncapi/generator-react-sdk';
2 | import { ChannelPool } from '../../../components/templates/channelpool';
3 |
4 | export default function ({ asyncapi, params }) {
5 | return (
6 |
7 | {render()}
8 |
9 | );
10 | }
11 |
--------------------------------------------------------------------------------
/template/src/Services/Interfaces/iamqpservice.js:
--------------------------------------------------------------------------------
1 | import { File, render } from '@asyncapi/generator-react-sdk';
2 | import { IAmqpService } from '../../../../components/templates/amqpservice.interface';
3 |
4 | export default function ({ asyncapi, params }) {
5 | return (
6 |
7 | {render()}
8 |
9 | );
10 | }
11 |
--------------------------------------------------------------------------------
/template/src/Services/Interfaces/ichannelpool.js:
--------------------------------------------------------------------------------
1 | import { File, render } from '@asyncapi/generator-react-sdk';
2 | import { IChannelPool } from '../../../../components/templates/channelpool.interface';
3 |
4 | export default function ({ asyncapi, params }) {
5 | return (
6 |
7 | {render()}
8 |
9 | );
10 | }
11 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | All notable changes to `BrokerAPI` will be documented in this file.
4 |
5 | Updates should follow the [Keep a CHANGELOG](http://keepachangelog.com/) principles.
6 |
7 | ## NEXT - 2021-01-19
8 |
9 | ### Added
10 | - Full support for RPC calls
11 |
12 | ### Deprecated
13 | - Nothing
14 |
15 | ### Fixed
16 | - Nothing
17 |
18 | ### Removed
19 | - Nothing
20 |
21 | ### Security
22 | - Nothing
23 |
--------------------------------------------------------------------------------
/CODEOWNERS:
--------------------------------------------------------------------------------
1 | # This file provides an overview of code owners in this repository.
2 |
3 | # Each line is a file pattern followed by one or more owners.
4 | # The last matching pattern has the most precedence.
5 | # For more details, read the following article on GitHub: https://help.github.com/articles/about-codeowners/.
6 |
7 | # The default owners are automatically added as reviewers when you open a pull request unless different owners are specified in the file.
8 | * @mr-nuno @connil @asyncapi-bot-eve
--------------------------------------------------------------------------------
/components/templates/channelpool.interface.js:
--------------------------------------------------------------------------------
1 | const template = (asyncapi, params) => `using System;
2 | using RabbitMQ.Client;
3 |
4 | namespace ${params.namespace}.Services.Interfaces;
5 |
6 | ///
7 | /// Channel pool holding all channels for a async api specification
8 | ///
9 | public interface IChannelPool : IDisposable
10 | {
11 | ///
12 | /// Get a channel for a operation
13 | ///
14 | /// The operation id specified in the async api specification
15 | /// A channel
16 | IModel GetChannel(string operationId);
17 | }`;
18 |
19 | export function IChannelPool({ asyncapi, params }) {
20 | return template(asyncapi, params);
21 | }
22 |
--------------------------------------------------------------------------------
/template/src/worker.js:
--------------------------------------------------------------------------------
1 | import { File, render } from '@asyncapi/generator-react-sdk';
2 | import { Consumers } from '../../components/Consumers';
3 | import { Publishers } from '../../components/Publishers';
4 | import { Worker } from '../../components/Worker';
5 | import { getChannels } from '../../utils/common';
6 |
7 | export default function ({ asyncapi, params }) {
8 | const channels = getChannels(asyncapi);
9 |
10 | if (channels.length === 0) {
11 | return null;
12 | }
13 |
14 | return (
15 |
16 |
17 | {render()}
18 | {render()}
19 |
20 |
21 | );
22 | }
23 |
--------------------------------------------------------------------------------
/components/Publishers.js:
--------------------------------------------------------------------------------
1 | export function Publishers({ channels }) {
2 | if (channels.length === 0) {
3 | return null;
4 | }
5 |
6 | return `
7 | // Code for the publisher: Send message on custom events, below is a timing example.
8 | // A real world example would probably read temeratures from some kind of I/O temperature sensor.
9 | /*
10 | var rnd = new Random((int) DateTime.Now.Ticks);
11 | while (!stoppingToken.IsCancellationRequested)
12 | {
13 | var message = new ${channels[0].publisher.messageType}();
14 | _amqpService.${channels[0].publisher.operationId}(message);
15 | await Task.Delay(rnd.Next(500, 3000), stoppingToken);
16 | }
17 | */
18 | `;
19 | }
20 |
--------------------------------------------------------------------------------
/ISSUE_TEMPLATE.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## Detailed description
4 |
5 | Provide a detailed description of the change or addition you are proposing.
6 |
7 | Make it clear if the issue is a bug, an enhancement or just a question.
8 |
9 | ## Context
10 |
11 | Why is this change important to you? How would you use it?
12 |
13 | How can it benefit other users?
14 |
15 | ## Possible implementation
16 |
17 | Not obligatory, but suggest an idea for implementing addition or change.
18 |
19 | ## Your environment
20 |
21 | Include as many relevant details about the environment you experienced the bug in and how to reproduce it.
22 |
23 | * Version used (e.g. PHP 5.6, HHVM 3):
24 | * Operating system and version (e.g. Ubuntu 16.04, Windows 7):
25 | * Link to your project:
26 | * ...
27 | * ...
28 |
--------------------------------------------------------------------------------
/template/readme.js:
--------------------------------------------------------------------------------
1 | import { File } from '@asyncapi/generator-react-sdk';
2 | import { getChannels } from '../utils/common';
3 |
4 | export default function ({ asyncapi, params }) {
5 | if (!asyncapi.hasComponents()) {
6 | return null;
7 | }
8 |
9 | const publishers = getChannels(asyncapi).filter(
10 | (channel) => channel.isPublish
11 | );
12 | const consumers = getChannels(asyncapi).filter(
13 | (channel) => !channel.isPublish
14 | );
15 |
16 | return (
17 | {`
18 | # RabbitMq Client for ${asyncapi.id()}
19 | ## IAmqpService
20 | This interface describes the channels in the specification.
21 | ### Consumers
22 | ${consumers.map((channel) => {
23 | return `${channel.routingKey} `;
24 | })}
25 | ### Publishers
26 | ${publishers.map((channel) => {
27 | return `${channel.routingKey} `;
28 | })}
29 |
30 | `}
31 | );
32 | }
33 |
--------------------------------------------------------------------------------
/template/src/docker.js:
--------------------------------------------------------------------------------
1 | import { File } from '@asyncapi/generator-react-sdk';
2 |
3 | export default function({ asyncapi, params }) {
4 | if (!asyncapi.hasComponents()) {
5 | return null;
6 | }
7 |
8 | return (
9 |
10 | {`FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
11 | FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
12 |
13 | WORKDIR /app
14 |
15 | ARG VERSION=0.0.0.0
16 |
17 | WORKDIR /src
18 |
19 | COPY ["${params.namespace}.csproj", "/src"]
20 | RUN dotnet restore "${params.namespace}.csproj"
21 |
22 | COPY . .
23 | WORKDIR "/src"
24 | RUN dotnet build "${params.namespace}.csproj" /p:NuGetVersion=\${VERSION} /p:Version=\${VERSION} -c Release -o /app/build --no-restore
25 |
26 | FROM build AS publish
27 | RUN dotnet publish "${params.namespace}.csproj" -c Release -o /app/publish --no-restore
28 |
29 | FROM base AS final
30 | WORKDIR /app
31 | COPY --from=publish /app/publish .
32 |
33 | ENTRYPOINT ["dotnet", "${params.namespace}.dll"]`
34 | }
35 |
36 | );
37 | }
38 |
--------------------------------------------------------------------------------
/.allcontributorsrc:
--------------------------------------------------------------------------------
1 | {
2 | "projectName": "dotnet-rabbitmq-template",
3 | "projectOwner": "@asyncapi",
4 | "repoType": "github",
5 | "repoHost": "https://github.com",
6 | "files": [
7 | "README.md"
8 | ],
9 | "imageSize": 100,
10 | "commit": false,
11 | "contributors": [
12 | {
13 | "login": "mr-nuno",
14 | "name": "Peter Wikström",
15 | "avatar_url": "https://avatars.githubusercontent.com/u/1067841?v=4",
16 | "profile": "https://github.com/mr-nuno",
17 | "contributions": [
18 | "code",
19 | "maintenance",
20 | "question",
21 | "ideas",
22 | "doc",
23 | "bug",
24 | "review"
25 | ]
26 | },
27 | {
28 | "login": "connil",
29 | "name": "Conny Nilimaa",
30 | "avatar_url": "https://avatars.githubusercontent.com/u/6583798?v=4",
31 | "profile": "https://github.com/connil",
32 | "contributions": [
33 | "review"
34 | ]
35 | }
36 | ],
37 | "contributorsPerLine": 7,
38 | "commitConvention": "none"
39 | }
40 |
--------------------------------------------------------------------------------
/components/Worker.js:
--------------------------------------------------------------------------------
1 | export function Worker({ asyncapi, params, childrenContent }) {
2 | return `using System;
3 | using System.Threading;
4 | using System.Threading.Tasks;
5 | using ${params.namespace}.Models;
6 | using Microsoft.Extensions.Configuration;
7 | using Microsoft.Extensions.Hosting;
8 | using ${params.namespace}.Services;
9 |
10 | namespace ${params.namespace}
11 | {
12 | ///
13 | /// Generated worker for ${asyncapi.info().title()}, ${asyncapi
14 | .info()
15 | .version()}
16 | ///
17 | public class Worker : BackgroundService
18 | {
19 | private readonly AmqpService _amqpService;
20 |
21 | public Worker(IConfiguration configuration)
22 | {
23 | _amqpService = new AmqpService(configuration);
24 | }
25 |
26 | protected override Task ExecuteAsync(CancellationToken stoppingToken)
27 | {
28 | ${childrenContent}
29 | return Task.CompletedTask;
30 | }
31 |
32 | public override void Dispose()
33 | {
34 | base.Dispose();
35 | _amqpService.Dispose();
36 | }
37 | }
38 | }`;
39 | }
40 |
--------------------------------------------------------------------------------
/template/src/project.js:
--------------------------------------------------------------------------------
1 | import { File } from '@asyncapi/generator-react-sdk';
2 |
3 | export default function ({ asyncapi, params }) {
4 | if (!asyncapi.hasComponents()) {
5 | return null;
6 | }
7 |
8 | return (
9 |
10 | {`
11 |
12 | net7.0
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 | `}
26 |
27 | );
28 | }
29 |
--------------------------------------------------------------------------------
/template/src/Models/model.js:
--------------------------------------------------------------------------------
1 | import { File } from '@asyncapi/generator-react-sdk';
2 | import { CSharpGenerator, CSHARP_COMMON_PRESET, FormatHelpers } from '@asyncapi/modelina';
3 |
4 | /**
5 | * @typedef RenderArgument
6 | * @type {object}
7 | * @property {AsyncAPIDocument} asyncapi received from the generator.
8 | */
9 |
10 | /**
11 | * Render all schema models
12 | * @param {RenderArgument} param0
13 | * @returns
14 | */
15 | export default async function modelRenderer({ asyncapi, params }) {
16 | const typescriptGenerator = new CSharpGenerator({presets: [{preset: CSHARP_COMMON_PRESET}]});
17 | const generatedModels = await typescriptGenerator.generate(asyncapi);
18 | const files = [];
19 | for (const generatedModel of generatedModels) {
20 | const className = FormatHelpers.toPascalCase(generatedModel.modelName);
21 | const modelFileName = `${className}.cs`;
22 | const fileContent = `
23 | ${generatedModel.dependencies.join('\n')}
24 | // autogenerated by @asyncapi/modelina - https://github.com/asyncapi/modelina
25 | namespace ${params.namespace}.Models {
26 | ${generatedModel.result}
27 | }
28 | `;
29 | files.push({fileContent});
30 | }
31 | return files;
32 | }
33 |
34 |
--------------------------------------------------------------------------------
/.github/workflows/update-maintainers-trigger.yaml:
--------------------------------------------------------------------------------
1 | # This action is centrally managed in https://github.com/asyncapi/.github/
2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo
3 |
4 | name: Trigger MAINTAINERS.yaml file update
5 |
6 | on:
7 | push:
8 | branches: [ master ]
9 | paths:
10 | # Check all valid CODEOWNERS locations:
11 | # https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners#codeowners-file-location
12 | - 'CODEOWNERS'
13 | - '.github/CODEOWNERS'
14 | - '.docs/CODEOWNERS'
15 |
16 | jobs:
17 | trigger-maintainers-update:
18 | name: Trigger updating MAINTAINERS.yaml because of CODEOWNERS change
19 | runs-on: ubuntu-latest
20 |
21 | steps:
22 | - name: Repository Dispatch
23 | uses: peter-evans/repository-dispatch@ff45666b9427631e3450c54a1bcbee4d9ff4d7c0 # https://github.com/peter-evans/repository-dispatch/releases/tag/v3.0.0
24 | with:
25 | # The PAT with the 'public_repo' scope is required
26 | token: ${{ secrets.GH_TOKEN }}
27 | repository: ${{ github.repository_owner }}/community
28 | event-type: trigger-maintainers-update
29 |
--------------------------------------------------------------------------------
/.github/workflows/automerge-for-humans-remove-ready-to-merge-label-on-edit.yml:
--------------------------------------------------------------------------------
1 | # This workflow is centrally managed in https://github.com/asyncapi/.github/
2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo
3 |
4 | # Defence from evil contributor that after adding `ready-to-merge` all suddenly makes evil commit or evil change in PR title
5 | # Label is removed once above action is detected
6 | name: Remove ready-to-merge label
7 |
8 | on:
9 | pull_request_target:
10 | types:
11 | - synchronize
12 | - edited
13 |
14 | jobs:
15 | remove-ready-label:
16 | runs-on: ubuntu-latest
17 | steps:
18 | - name: Remove label
19 | uses: actions/github-script@v7
20 | with:
21 | github-token: ${{ secrets.GH_TOKEN }}
22 | script: |
23 | const labelToRemove = 'ready-to-merge';
24 | const labels = context.payload.pull_request.labels;
25 | const isLabelPresent = labels.some(label => label.name === labelToRemove)
26 | if(!isLabelPresent) return;
27 | github.rest.issues.removeLabel({
28 | issue_number: context.issue.number,
29 | owner: context.repo.owner,
30 | repo: context.repo.repo,
31 | name: labelToRemove
32 | })
33 |
--------------------------------------------------------------------------------
/components/templates/amqpservice.interface.js:
--------------------------------------------------------------------------------
1 | import { getChannels, toPascalCase } from '../../utils/common';
2 |
3 | const template = (channels, params) => `using System;
4 | using ${params.namespace}.Models;
5 |
6 | namespace ${params.namespace}.Services.Interfaces;
7 |
8 | public interface IAmqpService : IDisposable
9 | {
10 | ${channels
11 | .filter((channel) => channel.publisher)
12 | .map(
13 | (channel) => `
14 | ///
15 | /// Publish operation from ${channel.routingKey}
16 | ///
17 | /// The message to be handled by this amqp operation
18 | void ${toPascalCase(channel.publisher.operationId)}(${toPascalCase(
19 | channel.publisher.messageType
20 | )} message);
21 |
22 | `
23 | )
24 | .join('')}
25 |
26 | ${channels
27 | .filter((channel) => channel.subscriber)
28 | .map(
29 | (channel) => `
30 | ///
31 | /// Subscribe operation from ${channel.routingKey}
32 | ///
33 | void ${toPascalCase(channel.subscriber.operationId)}();
34 |
35 | `
36 | )
37 | .join('')}
38 | }`;
39 |
40 | export function IAmqpService({ asyncapi, params }) {
41 | const channels = getChannels(asyncapi);
42 |
43 | if (channels.length === 0) {
44 | return null;
45 | }
46 |
47 | return template(channels, params);
48 | }
49 |
--------------------------------------------------------------------------------
/template/src/program.js:
--------------------------------------------------------------------------------
1 | import { File } from '@asyncapi/generator-react-sdk';
2 |
3 | export default function({ asyncapi, params }) {
4 | if (!asyncapi.hasComponents()) {
5 | return null;
6 | }
7 |
8 | return (
9 |
10 | {`using Masking.Serilog;
11 | using Microsoft.AspNetCore.Hosting;
12 | using Microsoft.Extensions.DependencyInjection;
13 | using Microsoft.Extensions.Hosting;
14 | using Serilog;
15 |
16 | namespace ${params.namespace}
17 | {
18 | public class Program
19 | {
20 | public static void Main(string[] args)
21 | {
22 | CreateHostBuilder(args).Build().Run();
23 | }
24 |
25 | public static IHostBuilder CreateHostBuilder(string[] args) =>
26 | Host.CreateDefaultBuilder(args)
27 | .UseSerilog((hostingContext, loggerConfiguration) =>
28 | loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration)
29 | .Destructure.ByMaskingProperties("Password", "Token"))
30 | .ConfigureServices((hostContext, services) =>
31 | {
32 | services.AddHostedService();
33 | })
34 | .ConfigureWebHostDefaults(webBuilder =>
35 | {
36 | webBuilder.UseStartup();
37 | });
38 | }
39 | }`
40 | }
41 |
42 | );
43 | }
44 |
--------------------------------------------------------------------------------
/template/src/startup.js:
--------------------------------------------------------------------------------
1 | import { File } from '@asyncapi/generator-react-sdk';
2 |
3 | export default function({ asyncapi, params }) {
4 | if (!asyncapi.hasComponents()) {
5 | return null;
6 | }
7 |
8 | return (
9 |
10 | {`using Microsoft.AspNetCore.Builder;
11 | using Microsoft.AspNetCore.Hosting;
12 | using Microsoft.Extensions.DependencyInjection;
13 | using Microsoft.Extensions.Hosting;
14 |
15 | namespace ${params.namespace}
16 | {
17 | public class Startup
18 | {
19 | // This method gets called by the runtime. Use this method to add services to the container.
20 | // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
21 | public void ConfigureServices(IServiceCollection services)
22 | {
23 | services.AddControllers();
24 | }
25 |
26 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
27 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
28 | {
29 | if (env.IsDevelopment())
30 | {
31 | app.UseDeveloperExceptionPage();
32 | }
33 |
34 | app.UseRouting();
35 | app.UseEndpoints(endpoints =>
36 | {
37 | endpoints.MapControllers();
38 | });
39 | }
40 | }
41 | }`
42 | }
43 |
44 | );
45 | }
46 |
--------------------------------------------------------------------------------
/.github/workflows/autoupdate.yml:
--------------------------------------------------------------------------------
1 | # This action is centrally managed in https://github.com/asyncapi/.github/
2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo
3 |
4 | # This workflow is designed to work with:
5 | # - autoapprove and automerge workflows for dependabot and asyncapibot.
6 | # - special release branches that we from time to time create in upstream repos. If we open up PRs for them from the very beginning of the release, the release branch will constantly update with new things from the destination branch they are opened against
7 |
8 | # It uses GitHub Action that auto-updates pull requests branches, whenever changes are pushed to their destination branch.
9 | # Autoupdating to latest destination branch works only in the context of upstream repo and not forks
10 |
11 | name: autoupdate
12 |
13 | on:
14 | push:
15 | branches-ignore:
16 | - 'version-bump/**'
17 | - 'dependabot/**'
18 | - 'bot/**'
19 | - 'all-contributors/**'
20 |
21 | jobs:
22 | autoupdate-for-bot:
23 | if: startsWith(github.repository, 'asyncapi/')
24 | name: Autoupdate autoapproved PR created in the upstream
25 | runs-on: ubuntu-latest
26 | steps:
27 | - name: Autoupdating
28 | uses: docker://chinthakagodawita/autoupdate-action:v1
29 | env:
30 | GITHUB_TOKEN: '${{ secrets.GH_TOKEN_BOT_EVE }}'
31 | PR_FILTER: "labelled"
32 | PR_LABELS: "autoupdate"
33 | PR_READY_STATE: "ready_for_review"
34 | MERGE_CONFLICT_ACTION: "ignore"
35 |
--------------------------------------------------------------------------------
/.github/workflows/bump.yml:
--------------------------------------------------------------------------------
1 | # This action is centrally managed in https://github.com/asyncapi/.github/
2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo
3 |
4 | # Purpose of this action is to update npm package in libraries that use it. It is like dependabot for asyncapi npm modules only.
5 | # It runs in a repo after merge of release commit and searches for other packages that use released package. Every found package gets updated with lates version
6 |
7 | name: Bump package version in dependent repos - if Node project
8 |
9 | on:
10 | # It cannot run on release event as when release is created then version is not yet bumped in package.json
11 | # This means we cannot extract easily latest version and have a risk that package is not yet on npm
12 | push:
13 | branches:
14 | - master
15 |
16 | jobs:
17 | bump-in-dependent-projects:
18 | name: Bump this package in repositories that depend on it
19 | if: startsWith(github.event.commits[0].message, 'chore(release):')
20 | runs-on: ubuntu-latest
21 | steps:
22 | - name: Checkout repo
23 | uses: actions/checkout@v2
24 | - name: Check if Node.js project and has package.json
25 | id: packagejson
26 | run: test -e ./package.json && echo "::set-output name=exists::true" || echo "::set-output name=exists::false"
27 | - if: steps.packagejson.outputs.exists == 'true'
28 | name: Bumping latest version of this package in other repositories
29 | uses: derberg/npm-dependency-manager-for-your-github-org@v4
30 | with:
31 | github_token: ${{ secrets.GH_TOKEN }}
32 | committer_username: asyncapi-bot
33 | committer_email: info@asyncapi.io
34 | repos_to_ignore: html-template # this is temporary until react component releases 1.0, then it can be removed
35 |
--------------------------------------------------------------------------------
/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## Description
4 |
5 | Describe your changes in detail.
6 |
7 | ## Motivation and context
8 |
9 | Why is this change required? What problem does it solve?
10 |
11 | If it fixes an open issue, please link to the issue here (if you write `fixes #num`
12 | or `closes #num`, the issue will be automatically closed when the pull is accepted.)
13 |
14 | ## How has this been tested?
15 |
16 | Please describe in detail how you tested your changes.
17 |
18 | Include details of your testing environment, and the tests you ran to
19 | see how your change affects other areas of the code, etc.
20 |
21 | ## Screenshots (if appropriate)
22 |
23 | ## Types of changes
24 |
25 | What types of changes does your code introduce? Put an `x` in all the boxes that apply:
26 | - [ ] Bug fix (non-breaking change which fixes an issue)
27 | - [ ] New feature (non-breaking change which adds functionality)
28 | - [ ] Breaking change (fix or feature that would cause existing functionality to change)
29 |
30 | ## Checklist:
31 |
32 | Go over all the following points, and put an `x` in all the boxes that apply.
33 |
34 | Please, please, please, don't send your pull request until all of the boxes are ticked. Once your pull request is created, it will trigger a build on our [continuous integration](http://www.phptherightway.com/#continuous-integration) server to make sure your [tests and code style pass](https://help.github.com/articles/about-required-status-checks/).
35 |
36 | - [ ] I have read the **[CONTRIBUTING](CONTRIBUTING.md)** document.
37 | - [ ] My pull request addresses exactly one patch/feature.
38 | - [ ] I have created a branch for this patch/feature.
39 | - [ ] Each individual commit in the pull request is meaningful.
40 | - [ ] I have added tests to cover my changes.
41 | - [ ] If my change requires a change to the documentation, I have updated it accordingly.
42 |
43 | If you're unsure about any of these, don't hesitate to ask. We're here to help!
44 |
--------------------------------------------------------------------------------
/template/src/appconfig.js:
--------------------------------------------------------------------------------
1 | import { File } from '@asyncapi/generator-react-sdk';
2 |
3 | /*
4 | * Each template to be rendered must have as a root component a File component,
5 | * otherwise it will be skipped.
6 | *
7 | * If you don't want to render anything, you can return `null` or `undefined` and then Generator will skip the given template.
8 | *
9 | * Below you can see how reusable chunks (components) could be called.
10 | * Just write a new component (or import it) and place it inside the File or another component.
11 | *
12 | * Notice that you can pass parameters to components. In fact, underneath, each component is a pure Javascript function.
13 | */
14 | export default function ({ asyncapi, params }) {
15 | if (!asyncapi.hasComponents()) {
16 | return null;
17 | }
18 |
19 | // Notice that root component is the `File` component.
20 | return (
21 |
22 | {`{
23 | "Serilog": {
24 | "MinimumLevel": {
25 | "Default": "Verbose",
26 | "Override": {
27 | "System": "Error",
28 | "Microsoft": "Information",
29 | "Microsoft.AspNetCore.Authentication": "Information",
30 | "Microsoft.EntityFrameworkCore": "Error",
31 | "Microsoft.AspNetCore.Hosting.Diagnostics": "Error",
32 | "Microsoft.AspNetCore.Routing.EndpointMiddleware": "Error",
33 | "Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker": "Error",
34 | "Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor": "Error"
35 | }
36 | },
37 | "Properties": {
38 | "Process": "${params.namespace}"
39 | },
40 | "WriteTo": [
41 | {
42 | "Name": "Console"
43 | },
44 | {
45 | "Name": "Seq",
46 | "Args":
47 | {
48 | "serverUrl": "http://localhost:5341",
49 | "apiKey" : ""
50 | }
51 | }
52 | ],
53 | "Enrich": [
54 | "FromLogContext"
55 | ]
56 | },
57 | "RabbitMq": {
58 | "User": "user",
59 | "Password": "password",
60 | "Host": "host/vhost"
61 | }
62 | }`}
63 |
64 | );
65 | }
66 |
--------------------------------------------------------------------------------
/.github/workflows/automerge.yml:
--------------------------------------------------------------------------------
1 | # This action is centrally managed in https://github.com/asyncapi/.github/
2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo.
3 |
4 | name: Automerge PRs from bots
5 |
6 | on:
7 | pull_request_target:
8 | types:
9 | - opened
10 | - synchronize
11 |
12 | jobs:
13 | autoapprove-for-bot:
14 | name: Autoapprove PR comming from a bot
15 | if: >
16 | contains(fromJson('["asyncapi-bot", "dependabot[bot]", "dependabot-preview[bot]"]'), github.event.pull_request.user.login) &&
17 | contains(fromJson('["asyncapi-bot", "dependabot[bot]", "dependabot-preview[bot]"]'), github.actor) &&
18 | !contains(github.event.pull_request.labels.*.name, 'released')
19 | runs-on: ubuntu-latest
20 | steps:
21 | - name: Autoapproving
22 | uses: hmarr/auto-approve-action@44888193675f29a83e04faf4002fa8c0b537b1e4 # v3.2.1 is used https://github.com/hmarr/auto-approve-action/releases/tag/v3.2.1
23 | with:
24 | github-token: "${{ secrets.GH_TOKEN_BOT_EVE }}"
25 |
26 | - name: Label autoapproved
27 | uses: actions/github-script@v7
28 | with:
29 | github-token: ${{ secrets.GH_TOKEN }}
30 | script: |
31 | github.rest.issues.addLabels({
32 | issue_number: context.issue.number,
33 | owner: context.repo.owner,
34 | repo: context.repo.repo,
35 | labels: ['autoapproved', 'autoupdate']
36 | })
37 |
38 | automerge-for-bot:
39 | name: Automerge PR autoapproved by a bot
40 | needs: [autoapprove-for-bot]
41 | runs-on: ubuntu-latest
42 | steps:
43 | - name: Automerging
44 | uses: pascalgn/automerge-action@22948e0bc22f0aa673800da838595a3e7347e584 #v0.15.6 https://github.com/pascalgn/automerge-action/releases/tag/v0.15.6
45 | env:
46 | GITHUB_TOKEN: "${{ secrets.GH_TOKEN }}"
47 | GITHUB_LOGIN: asyncapi-bot
48 | MERGE_LABELS: "!do-not-merge"
49 | MERGE_METHOD: "squash"
50 | MERGE_COMMIT_MESSAGE: "{pullRequest.title} (#{pullRequest.number})"
51 | MERGE_RETRIES: "20"
52 | MERGE_RETRY_SLEEP: "30000"
53 |
--------------------------------------------------------------------------------
/example/publisher.yaml:
--------------------------------------------------------------------------------
1 | asyncapi: 2.2.0
2 | id: urn:com:lkab:rmq:iot:temperature-sensor
3 | info:
4 | title: Temperature sensor API
5 | contact:
6 | name: LKAB Support
7 | url: https://www.asyncapi.org/support
8 | email: support@lkab.com
9 | version: 1.0.3
10 | description: |
11 | The temperature API provides temperature change from sensors
12 | license:
13 | name: Apache 2.0
14 | url: 'https://www.apache.org/licenses/LICENSE-2.0'
15 | tags:
16 | - name: iot
17 | description: Tag for iot services
18 | servers:
19 | production:
20 | url: goose.rmq2.cloudamqp.com/hohmawct
21 | protocol: amqps
22 | channels:
23 | 'lkab.iot.v1.{sensorId}.temperature':
24 | parameters:
25 | sensorId:
26 | description: 'Id of the temperature sensor. Use # to get temperatures from all sensors'
27 | x-example: SENSOR-001
28 | schema:
29 | type: string
30 | subscribe:
31 | operationId: onSensorTemperatureChange
32 | description: Recieve a temperature change from a sensor
33 | message:
34 | correlationId:
35 | location: $message.header#/correlation_id
36 | name: Temperature
37 | payload:
38 | $ref: '#/components/schemas/temperature'
39 | bindings:
40 | amqp:
41 | is: routingKey
42 | queue:
43 | name: temperatures
44 | x-prefetch-count: 100
45 | x-confirm: true
46 | exchange:
47 | name: lkab.iot.temperature
48 | type: topic
49 | durable: true
50 | autoDelete: false
51 | vhost: iot
52 | components:
53 | schemas:
54 | temperature:
55 | type: object
56 | properties:
57 | origin:
58 | type: string
59 | description: The origin of this temperature
60 | celcius:
61 | type: number
62 | description: Temperature measured in Celcius
63 | kelvin:
64 | type: number
65 | description: Temperature measured in Kelvin
66 | fahrenheit:
67 | type: number
68 | format: number
69 | description: Temperature measured in Fahrenheit
70 | created:
71 | type: string
72 | format: date-time
73 | description: Date and time when the tempreture was measured.
74 |
--------------------------------------------------------------------------------
/.github/workflows/please-take-a-look-command.yml:
--------------------------------------------------------------------------------
1 | # This action is centrally managed in https://github.com/asyncapi/.github/
2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo
3 |
4 | # It uses Github actions to listen for comments on issues and pull requests and
5 | # if the comment contains /please-take-a-look or /ptal it will add a comment pinging
6 | # the code-owners who are reviewers for PR
7 |
8 | name: Please take a Look
9 |
10 | on:
11 | issue_comment:
12 | types: [created]
13 |
14 | jobs:
15 | ping-for-attention:
16 | if: >
17 | github.event.issue.pull_request &&
18 | github.event.issue.state != 'closed' &&
19 | github.actor != 'asyncapi-bot' &&
20 | (
21 | contains(github.event.comment.body, '/please-take-a-look') ||
22 | contains(github.event.comment.body, '/ptal') ||
23 | contains(github.event.comment.body, '/PTAL')
24 | )
25 | runs-on: ubuntu-latest
26 | steps:
27 | - name: Check for Please Take a Look Command
28 | uses: actions/github-script@v7
29 | with:
30 | github-token: ${{ secrets.GH_TOKEN }}
31 | script: |
32 | const prDetailsUrl = context.payload.issue.pull_request.url;
33 | const { data: pull } = await github.request(prDetailsUrl);
34 | const reviewers = pull.requested_reviewers.map(reviewer => reviewer.login);
35 |
36 | const { data: reviews } = await github.rest.pulls.listReviews({
37 | owner: context.repo.owner,
38 | repo: context.repo.repo,
39 | pull_number: context.issue.number
40 | });
41 |
42 | const reviewersWhoHaveReviewed = reviews.map(review => review.user.login);
43 |
44 | const reviewersWhoHaveNotReviewed = reviewers.filter(reviewer => !reviewersWhoHaveReviewed.includes(reviewer));
45 |
46 | if (reviewersWhoHaveNotReviewed.length > 0) {
47 | const comment = reviewersWhoHaveNotReviewed.filter(reviewer => reviewer !== 'asyncapi-bot-eve' ).map(reviewer => `@${reviewer}`).join(' ');
48 | await github.rest.issues.createComment({
49 | issue_number: context.issue.number,
50 | owner: context.repo.owner,
51 | repo: context.repo.repo,
52 | body: `${comment} Please take a look at this PR. Thanks! :wave:`
53 | });
54 | }
55 |
--------------------------------------------------------------------------------
/.github/workflows/transfer-issue.yml:
--------------------------------------------------------------------------------
1 | # This action is centrally managed in https://github.com/asyncapi/.github/
2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo
3 |
4 | name: Transfer Issues between repositories
5 |
6 | on:
7 | issue_comment:
8 | types:
9 | - created
10 |
11 | permissions:
12 | issues: write
13 |
14 | jobs:
15 | transfer:
16 | if: ${{(!github.event.issue.pull_request && github.event.issue.state != 'closed' && github.actor != 'asyncapi-bot') && (startsWith(github.event.comment.body, '/transfer-issue') || startsWith(github.event.comment.body, '/ti'))}}
17 | runs-on: ubuntu-latest
18 | steps:
19 | - name: Checkout Repository
20 | uses: actions/checkout@v4
21 | - name: Extract Input
22 | id: extract_step
23 | env:
24 | COMMENT: "${{ github.event.comment.body }}"
25 | run: |
26 | REPO=$(echo "$COMMENT" | awk '{print $2}')
27 | echo "repo=$REPO" >> $GITHUB_OUTPUT
28 | - name: Check Repo
29 | uses: actions/github-script@v7
30 | with:
31 | github-token: ${{secrets.GH_TOKEN}}
32 | script: |
33 | const r = "${{github.repository}}"
34 | const [owner, repo] = r.split('/')
35 | const repoToMove = process.env.REPO_TO_MOVE
36 | const issue_number = context.issue.number
37 | try {
38 | const {data} = await github.rest.repos.get({
39 | owner,
40 | repo: repoToMove
41 | })
42 | }catch (e) {
43 | const body = `${repoToMove} is not a repo under ${owner}. You can only transfer issue to repos that belong to the same organization.`
44 | await github.rest.issues.createComment({
45 | owner,
46 | repo,
47 | issue_number,
48 | body
49 | })
50 | process.exit(1)
51 | }
52 | env:
53 | REPO_TO_MOVE: ${{steps.extract_step.outputs.repo}}
54 | - name: Transfer Issue
55 | id: transferIssue
56 | working-directory: ./
57 | run: |
58 | gh issue transfer "$ISSUE_NUMBER" "asyncapi/$REPO_NAME"
59 | env:
60 | GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
61 | ISSUE_NUMBER: ${{ github.event.issue.number }}
62 | REPO_NAME: ${{ steps.extract_step.outputs.repo }}
63 |
--------------------------------------------------------------------------------
/.github/workflows/lint-pr-title.yml:
--------------------------------------------------------------------------------
1 | # This action is centrally managed in https://github.com/asyncapi/.github/
2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo
3 |
4 | name: Lint PR title
5 |
6 | on:
7 | pull_request_target:
8 | types: [opened, reopened, synchronize, edited, ready_for_review]
9 |
10 | jobs:
11 | lint-pr-title:
12 | name: Lint PR title
13 | runs-on: ubuntu-latest
14 | steps:
15 | # Since this workflow is REQUIRED for a PR to be mergable, we have to have this 'if' statement in step level instead of job level.
16 | - if: ${{ !contains(fromJson('["asyncapi-bot", "dependabot[bot]", "dependabot-preview[bot]", "allcontributors[bot]"]'), github.actor) }}
17 | uses: amannn/action-semantic-pull-request@c3cd5d1ea3580753008872425915e343e351ab54 #version 5.2.0 https://github.com/amannn/action-semantic-pull-request/releases/tag/v5.2.0
18 | id: lint_pr_title
19 | env:
20 | GITHUB_TOKEN: ${{ secrets.GH_TOKEN}}
21 | with:
22 | subjectPattern: ^(?![A-Z]).+$
23 | subjectPatternError: |
24 | The subject "{subject}" found in the pull request title "{title}" should start with a lowercase character.
25 |
26 | # Comments the error message from the above lint_pr_title action
27 | - if: ${{ always() && steps.lint_pr_title.outputs.error_message != null && !contains(fromJson('["asyncapi-bot", "dependabot[bot]", "dependabot-preview[bot]", "allcontributors[bot]"]'), github.actor)}}
28 | name: Comment on PR
29 | uses: marocchino/sticky-pull-request-comment@3d60a5b2dae89d44e0c6ddc69dd7536aec2071cd #use 2.5.0 https://github.com/marocchino/sticky-pull-request-comment/releases/tag/v2.5.0
30 | with:
31 | header: pr-title-lint-error
32 | GITHUB_TOKEN: ${{ secrets.GH_TOKEN}}
33 | message: |
34 |
35 | We require all PRs to follow [Conventional Commits specification](https://www.conventionalcommits.org/en/v1.0.0/).
36 | More details 👇🏼
37 | ```
38 | ${{ steps.lint_pr_title.outputs.error_message}}
39 | ```
40 | # deletes the error comment if the title is correct
41 | - if: ${{ steps.lint_pr_title.outputs.error_message == null }}
42 | name: delete the comment
43 | uses: marocchino/sticky-pull-request-comment@3d60a5b2dae89d44e0c6ddc69dd7536aec2071cd #use 2.5.0 https://github.com/marocchino/sticky-pull-request-comment/releases/tag/v2.5.0
44 | with:
45 | header: pr-title-lint-error
46 | delete: true
47 | GITHUB_TOKEN: ${{ secrets.GH_TOKEN}}
48 |
--------------------------------------------------------------------------------
/example/subscriber.yaml:
--------------------------------------------------------------------------------
1 | asyncapi: 2.2.0
2 | id: urn:com:lkab:rmq:iot:temperature-aggregator
3 | info:
4 | title: Temperature aggregator API
5 | contact:
6 | name: LKAB Support
7 | url: https://www.asyncapi.org/support
8 | email: support@lkab.com
9 | version: 1.0.3
10 | description: |
11 | The temperature API reads temperature chages from sensors
12 | license:
13 | name: Apache 2.0
14 | url: 'https://www.apache.org/licenses/LICENSE-2.0'
15 | tags:
16 | - name: iot
17 | description: Tag for iot services
18 | servers:
19 | production:
20 | url: goose.rmq2.cloudamqp.com/hohmawct
21 | protocol: amqps
22 | channels:
23 | 'lkab.aggregator.v1.{sensorId}.temperature':
24 | parameters:
25 | sensorId:
26 | description: 'Id of the temperature sensor. Use # to get temperatures from all sensors'
27 | x-example: SENSOR-001
28 | schema:
29 | type: string
30 | publish:
31 | operationId: onSpecificSensorTemperatureReceived
32 | description: Publish a temperature change from a specific sensor
33 | bindings:
34 | amqp:
35 | expiration: 100000
36 | userId: guest
37 | cc: ['lkab.user.logs']
38 | bcc: ['lkab.audit']
39 | priority: 10
40 | deliveryMode: 2
41 | mandatory: false
42 | replyTo: user.signedup
43 | timestamp: true
44 | ack: true
45 | message:
46 | correlationId:
47 | location: $message.header#/correlation_id
48 | name: Temperature
49 | payload:
50 | $ref: '#/components/schemas/temperature'
51 | bindings:
52 | amqp:
53 | is: routingKey
54 | exchange:
55 | x-alternate-exchange: lkab.iot.other
56 | name: lkab.iot.temperature
57 | type: topic
58 | durable: true
59 | autoDelete: false
60 | components:
61 | schemas:
62 | temperature:
63 | type: object
64 | properties:
65 | origin:
66 | type: string
67 | description: The origin of this temperature
68 | celcius:
69 | type: number
70 | description: Temperature measured in Celcius
71 | kelvin:
72 | type: number
73 | description: Temperature measured in Kelvin
74 | fahrenheit:
75 | type: number
76 | format: number
77 | description: Temperature measured in Fahrenheit
78 | created:
79 | type: string
80 | format: date-time
81 | description: Date and time when the tempreture was measured.
82 |
--------------------------------------------------------------------------------
/test/consumers.test.spec.js:
--------------------------------------------------------------------------------
1 | import { render } from '@asyncapi/generator-react-sdk';
2 | import AsyncAPIDocument from '@asyncapi/parser/lib/models/asyncapi';
3 | import { Consumers } from '../components/Consumers';
4 | import { cleanString, getChannels } from '../utils/common';
5 |
6 | describe('Consumers component', () => {
7 | it('should handle empty specification', () => {
8 | const asyncapi = new AsyncAPIDocument({
9 | asyncapi: '2.2.0',
10 | defaultContentType: 'application/json',
11 | });
12 |
13 | const expected = '';
14 |
15 | const result = render();
16 |
17 | expect(cleanString(result)).toEqual(cleanString(expected));
18 | });
19 |
20 | it('should render consumer implementation', () => {
21 | const asyncapi = new AsyncAPIDocument({
22 | asyncapi: '2.2.0',
23 | defaultContentType: 'application/json',
24 | channels: {
25 | '{sensorId}.temperature': {
26 | subscribe: {
27 | operationId: 'onSpecificSensorTemperatureReceived',
28 | description:
29 | 'Subscribe to a temperature change from a specific sensor.',
30 | message: {
31 | payload: {
32 | id: 'temperature',
33 | type: 'object',
34 | additionalProperties: false,
35 | properties: {
36 | celsius: { type: 'number', format: 'decimal' },
37 | kelvin: { type: 'number', format: 'decimal' },
38 | fahrenheit: { type: 'number', format: 'decimal' },
39 | origin: { type: ['null', 'string'] },
40 | created: { type: 'string', format: 'date-time' },
41 | },
42 | },
43 | name: 'temperature',
44 | },
45 | },
46 | parameters: {
47 | sensorId: {
48 | 'x-example': 'SENSOR-001',
49 | description: 'Id of the temperature sensor.',
50 | schema: { type: 'string' },
51 | },
52 | },
53 | bindings: {
54 | amqp: {
55 | is: 'routingKey',
56 | exchange: { name: 'temperature', type: 'topic', vhost: '/' },
57 | queue: { name: 'temperatures' },
58 | },
59 | },
60 | },
61 | },
62 | });
63 |
64 | const expected = `
65 | // Code for the subscriber: Recieves messages from RabbitMq
66 | _amqpService.OnSpecificSensorTemperatureReceived();
67 | `;
68 |
69 | const result = render();
70 |
71 | expect(cleanString(result)).toEqual(cleanString(expected));
72 | });
73 | });
74 |
--------------------------------------------------------------------------------
/test/iamqpservice.test.spec.js:
--------------------------------------------------------------------------------
1 | import { render } from '@asyncapi/generator-react-sdk';
2 | import AsyncAPIDocument from '@asyncapi/parser/lib/models/asyncapi';
3 | import { IAmqpService } from '../components/templates/amqpservice.interface';
4 | import { cleanString } from '../utils/common';
5 |
6 | describe('AMQP interface component', () => {
7 | it('should render a amqp service interface', () => {
8 | const asyncapi = new AsyncAPIDocument({
9 | asyncapi: '2.2.0',
10 | info: {
11 | title: 'Test',
12 | version: '1.0.0',
13 | },
14 | defaultContentType: 'application/json',
15 | channels: {
16 | '{sensorId}.temperature': {
17 | subscribe: {
18 | operationId: 'onSpecificSensorTemperatureReceived',
19 | description:
20 | 'Subscribe to a temperature change from a specific sensor.',
21 | message: {
22 | payload: {
23 | id: 'temperature',
24 | type: 'object',
25 | additionalProperties: false,
26 | properties: {
27 | celsius: { type: 'number', format: 'decimal' },
28 | kelvin: { type: 'number', format: 'decimal' },
29 | fahrenheit: { type: 'number', format: 'decimal' },
30 | origin: { type: ['null', 'string'] },
31 | created: { type: 'string', format: 'date-time' },
32 | },
33 | },
34 | name: 'temperature',
35 | },
36 | },
37 | parameters: {
38 | sensorId: {
39 | 'x-example': 'SENSOR-001',
40 | description: 'Id of the temperature sensor.',
41 | schema: { type: 'string' },
42 | },
43 | },
44 | bindings: {
45 | amqp: {
46 | is: 'routingKey',
47 | exchange: { name: 'temperature', type: 'topic', vhost: '/' },
48 | queue: { name: 'temperatures' },
49 | },
50 | },
51 | },
52 | },
53 | });
54 |
55 | const result = render(
56 |
57 | );
58 |
59 | expect(cleanString(result)).toContain(
60 | 'void OnSpecificSensorTemperatureReceived();'
61 | );
62 | });
63 |
64 | it('should handle empty specification', () => {
65 | const asyncapi = new AsyncAPIDocument({
66 | asyncapi: '2.2.0',
67 | defaultContentType: 'application/json',
68 | });
69 |
70 | const expected = '';
71 |
72 | const result = render();
73 |
74 | expect(cleanString(result)).toEqual(cleanString(expected));
75 | });
76 | });
77 |
--------------------------------------------------------------------------------
/.github/workflows/stale-issues-prs.yml:
--------------------------------------------------------------------------------
1 | # This action is centrally managed in https://github.com/asyncapi/.github/
2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo
3 |
4 | name: Manage stale issues and PRs
5 |
6 | on:
7 | schedule:
8 | - cron: "0 0 * * *"
9 |
10 | jobs:
11 | stale:
12 | if: startsWith(github.repository, 'asyncapi/')
13 | name: Mark issue or PR as stale
14 | runs-on: ubuntu-latest
15 | steps:
16 | - uses: actions/stale@5bef64f19d7facfb25b37b414482c7164d639639 #v9.1.0 but pointing to commit for security reasons
17 | with:
18 | repo-token: ${{ secrets.GITHUB_TOKEN }}
19 | stale-issue-message: |
20 | This issue has been automatically marked as stale because it has not had recent activity :sleeping:
21 |
22 | It will be closed in 120 days if no further activity occurs. To unstale this issue, add a comment with a detailed explanation.
23 |
24 | There can be many reasons why some specific issue has no activity. The most probable cause is lack of time, not lack of interest. AsyncAPI Initiative is a Linux Foundation project not owned by a single for-profit company. It is a community-driven initiative ruled under [open governance model](https://github.com/asyncapi/community/blob/master/CHARTER.md).
25 |
26 | Let us figure out together how to push this issue forward. Connect with us through [one of many communication channels](https://github.com/asyncapi/community/issues/1) we established here.
27 |
28 | Thank you for your patience :heart:
29 | stale-pr-message: |
30 | This pull request has been automatically marked as stale because it has not had recent activity :sleeping:
31 |
32 | It will be closed in 120 days if no further activity occurs. To unstale this pull request, add a comment with detailed explanation.
33 |
34 | There can be many reasons why some specific pull request has no activity. The most probable cause is lack of time, not lack of interest. AsyncAPI Initiative is a Linux Foundation project not owned by a single for-profit company. It is a community-driven initiative ruled under [open governance model](https://github.com/asyncapi/community/blob/master/CHARTER.md).
35 |
36 | Let us figure out together how to push this pull request forward. Connect with us through [one of many communication channels](https://github.com/asyncapi/community/issues/1) we established here.
37 |
38 | Thank you for your patience :heart:
39 | days-before-stale: 120
40 | days-before-close: 120
41 | stale-issue-label: stale
42 | stale-pr-label: stale
43 | exempt-issue-labels: keep-open
44 | exempt-pr-labels: keep-open
45 | close-issue-reason: not_planned
46 |
--------------------------------------------------------------------------------
/.github/workflows/scripts/mailchimp/index.js:
--------------------------------------------------------------------------------
1 | /**
2 | * This code is centrally managed in https://github.com/asyncapi/.github/
3 | * Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo
4 | */
5 | const mailchimp = require('@mailchimp/mailchimp_marketing');
6 | const core = require('@actions/core');
7 | const htmlContent = require('./htmlContent.js');
8 |
9 | /**
10 | * Sending API request to mailchimp to schedule email to subscribers
11 | * Input is the URL to issue/discussion or other resource
12 | */
13 | module.exports = async (link, title) => {
14 |
15 | let newCampaign;
16 |
17 | mailchimp.setConfig({
18 | apiKey: process.env.MAILCHIMP_API_KEY,
19 | server: 'us12'
20 | });
21 |
22 | /*
23 | * First we create campaign
24 | */
25 | try {
26 | newCampaign = await mailchimp.campaigns.create({
27 | type: 'regular',
28 | recipients: {
29 | list_id: '6e3e437abe',
30 | segment_opts: {
31 | match: 'any',
32 | conditions: [{
33 | condition_type: 'Interests',
34 | field: 'interests-2801e38b9f',
35 | op: 'interestcontains',
36 | value: ['f7204f9b90']
37 | }]
38 | }
39 | },
40 | settings: {
41 | subject_line: `TSC attention required: ${ title }`,
42 | preview_text: 'Check out the latest topic that TSC members have to be aware of',
43 | title: `New topic info - ${ new Date(Date.now()).toUTCString()}`,
44 | from_name: 'AsyncAPI Initiative',
45 | reply_to: 'info@asyncapi.io',
46 | }
47 | });
48 | } catch (error) {
49 | return core.setFailed(`Failed creating campaign: ${ JSON.stringify(error) }`);
50 | }
51 |
52 | /*
53 | * Content of the email is added separately after campaign creation
54 | */
55 | try {
56 | await mailchimp.campaigns.setContent(newCampaign.id, { html: htmlContent(link, title) });
57 | } catch (error) {
58 | return core.setFailed(`Failed adding content to campaign: ${ JSON.stringify(error) }`);
59 | }
60 |
61 | /*
62 | * We schedule an email to send it immediately
63 | */
64 | try {
65 | //schedule for next hour
66 | //so if this code was created by new issue creation at 9:46, the email is scheduled for 10:00
67 | //is it like this as schedule has limitiations and you cannot schedule email for 9:48
68 | const scheduleDate = new Date(Date.parse(new Date(Date.now()).toISOString()) + 1 * 1 * 60 * 60 * 1000);
69 | scheduleDate.setUTCMinutes(00);
70 |
71 | await mailchimp.campaigns.schedule(newCampaign.id, {
72 | schedule_time: scheduleDate.toISOString(),
73 | });
74 | } catch (error) {
75 | return core.setFailed(`Failed scheduling email: ${ JSON.stringify(error) }`);
76 | }
77 |
78 | core.info(`New email campaign created`);
79 | }
--------------------------------------------------------------------------------
/.eslintrc:
--------------------------------------------------------------------------------
1 | env:
2 | node: true
3 | es6: true
4 | jest/globals: true
5 |
6 | plugins:
7 | - sonarjs
8 | - jest
9 | - react
10 |
11 | extends:
12 | - eslint:recommended
13 | - plugin:jest/recommended
14 | - plugin:react/recommended
15 | - plugin:sonarjs/recommended
16 | - plugin:security/recommended
17 |
18 | parserOptions:
19 | ecmaVersion: 2018
20 | sourceType: module
21 | ecmaFeatures:
22 | jsx: true
23 | settings:
24 | react:
25 | version: detect
26 |
27 | rules:
28 | # Ignore Rules
29 | strict: 0
30 | no-underscore-dangle: 0
31 | no-mixed-requires: 0
32 | no-process-exit: 0
33 | no-warning-comments: 0
34 | curly: 0
35 | no-multi-spaces: 0
36 | no-alert: 0
37 | consistent-return: 0
38 | consistent-this: [0, self]
39 | func-style: 0
40 | max-nested-callbacks: 0
41 | camelcase: 0
42 |
43 | # Warnings
44 | no-debugger: 1
45 | no-empty: 1
46 | no-invalid-regexp: 1
47 | no-unused-expressions: 1
48 | no-native-reassign: 1
49 | no-fallthrough: 1
50 | sonarjs/cognitive-complexity: 1
51 |
52 | # Errors
53 | eqeqeq: 2
54 | no-undef: 2
55 | no-dupe-keys: 2
56 | no-empty-character-class: 2
57 | no-self-compare: 2
58 | valid-typeof: 2
59 | no-unused-vars: [2, { "args": "none" }]
60 | handle-callback-err: 2
61 | no-shadow-restricted-names: 2
62 | no-new-require: 2
63 | no-mixed-spaces-and-tabs: 2
64 | block-scoped-var: 2
65 | no-else-return: 2
66 | no-throw-literal: 2
67 | no-void: 2
68 | radix: 2
69 | wrap-iife: [2, outside]
70 | no-shadow: 0
71 | no-use-before-define: [2, nofunc]
72 | no-path-concat: 2
73 | valid-jsdoc: [0, {requireReturn: false, requireParamDescription: false, requireReturnDescription: false}]
74 |
75 | # stylistic errors
76 | no-spaced-func: 2
77 | semi-spacing: 2
78 | quotes: [2, 'single']
79 | key-spacing: [2, { beforeColon: false, afterColon: true }]
80 | indent: [2, 2]
81 | no-lonely-if: 2
82 | no-floating-decimal: 2
83 | brace-style: [2, 1tbs, { allowSingleLine: true }]
84 | comma-style: [2, last]
85 | no-multiple-empty-lines: [2, {max: 1}]
86 | no-nested-ternary: 2
87 | operator-assignment: [2, always]
88 | padded-blocks: [2, never]
89 | quote-props: [2, as-needed]
90 | keyword-spacing: [2, {'before': true, 'after': true, 'overrides': {}}]
91 | space-before-blocks: [2, always]
92 | array-bracket-spacing: [2, never]
93 | computed-property-spacing: [2, never]
94 | space-in-parens: [2, never]
95 | space-unary-ops: [2, {words: true, nonwords: false}]
96 | wrap-regex: 2
97 | linebreak-style: [2, unix]
98 | semi: [2, always]
99 | arrow-spacing: [2, {before: true, after: true}]
100 | no-class-assign: 2
101 | no-const-assign: 2
102 | no-dupe-class-members: 2
103 | no-this-before-super: 2
104 | no-var: 2
105 | object-shorthand: [2, always]
106 | prefer-arrow-callback: 2
107 | prefer-const: 2
108 | prefer-spread: 2
109 | prefer-template: 2
110 |
111 | # React
112 | react/jsx-uses-react: off
113 | react/react-in-jsx-scope: off
114 | react/display-name: off
115 | react/prop-types: off
--------------------------------------------------------------------------------
/.github/workflows/automerge-orphans.yml:
--------------------------------------------------------------------------------
1 | # This action is centrally managed in https://github.com/asyncapi/.github/
2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo
3 |
4 | name: 'Notify on failing automerge'
5 |
6 | on:
7 | schedule:
8 | - cron: "0 0 * * *"
9 |
10 | jobs:
11 | identify-orphans:
12 | if: startsWith(github.repository, 'asyncapi/')
13 | name: Find orphans and notify
14 | runs-on: ubuntu-latest
15 | steps:
16 | - name: Checkout repository
17 | uses: actions/checkout@v4
18 | - name: Get list of orphans
19 | uses: actions/github-script@v7
20 | id: orphans
21 | with:
22 | github-token: ${{ secrets.GITHUB_TOKEN }}
23 | script: |
24 | const query = `query($owner:String!, $name:String!) {
25 | repository(owner:$owner, name:$name){
26 | pullRequests(first: 100, states: OPEN){
27 | nodes{
28 | title
29 | url
30 | author {
31 | resourcePath
32 | }
33 | }
34 | }
35 | }
36 | }`;
37 | const variables = {
38 | owner: context.repo.owner,
39 | name: context.repo.repo
40 | };
41 | const { repository: { pullRequests: { nodes } } } = await github.graphql(query, variables);
42 |
43 | let orphans = nodes.filter( (pr) => pr.author.resourcePath === '/asyncapi-bot' || pr.author.resourcePath === '/apps/dependabot')
44 |
45 | if (orphans.length) {
46 | core.setOutput('found', 'true');
47 | //Yes, this is very naive approach to assume there is just one PR causing issues, there can be a case that more PRs are affected the same day
48 | //The thing is that handling multiple PRs will increase a complexity in this PR that in my opinion we should avoid
49 | //The other PRs will be reported the next day the action runs, or person that checks first url will notice the other ones
50 | core.setOutput('url', orphans[0].url);
51 | core.setOutput('title', orphans[0].title);
52 | }
53 | - if: steps.orphans.outputs.found == 'true'
54 | name: Convert markdown to slack markdown
55 | # This workflow is from our own org repo and safe to reference by 'master'.
56 | uses: asyncapi/.github/.github/actions/slackify-markdown@master # //NOSONAR
57 | id: issuemarkdown
58 | with:
59 | markdown: "-> [${{steps.orphans.outputs.title}}](${{steps.orphans.outputs.url}})"
60 | - if: steps.orphans.outputs.found == 'true'
61 | name: Send info about orphan to slack
62 | uses: rtCamp/action-slack-notify@c33737706dea87cd7784c687dadc9adf1be59990 # Using v2.3.2
63 | env:
64 | SLACK_WEBHOOK: ${{secrets.SLACK_CI_FAIL_NOTIFY}}
65 | SLACK_TITLE: 🚨 Not merged PR that should be automerged 🚨
66 | SLACK_MESSAGE: ${{steps.issuemarkdown.outputs.text}}
67 | MSG_MINIMAL: true
--------------------------------------------------------------------------------
/example/asyncapi.yaml:
--------------------------------------------------------------------------------
1 | asyncapi: 2.2.0
2 | id: urn:com:lkab:rmq:iot:temperature-sensor
3 | info:
4 | title: Temperature sensor API
5 | contact:
6 | name: LKAB Support
7 | url: https://www.asyncapi.org/support
8 | email: support@lkab.com
9 | version: 1.0.3
10 | description: |
11 | The temperature API provides channels send temperature change from sensors and reads temperature change from sensors
12 | license:
13 | name: Apache 2.0
14 | url: 'https://www.apache.org/licenses/LICENSE-2.0'
15 | tags:
16 | - name: iot
17 | description: Tag for iot services
18 | servers:
19 | production:
20 | url: goose.rmq2.cloudamqp.com/hohmawct
21 | protocol: amqps
22 | channels:
23 | 'lkab.iot.v1.{sensorId}.temperature':
24 | parameters:
25 | sensorId:
26 | description: 'Id of the temperature sensor. Use # to get temperatures from all sensors'
27 | x-example: SENSOR-001
28 | schema:
29 | type: string
30 | subscribe:
31 | operationId: onSensorTemperatureChange
32 | description: Recieve a temperature change from a sensor
33 | message:
34 | correlationId:
35 | location: $message.header#/correlation_id
36 | name: Temperature
37 | payload:
38 | $ref: '#/components/schemas/temperature'
39 | publish:
40 | operationId: onSpecificSensorTemperatureReceived
41 | description: Subscribe to a temperature change from a specific sensor
42 | bindings:
43 | amqp:
44 | expiration: 100000
45 | userId: guest
46 | cc: ['lkab.user.logs']
47 | bcc: ['lkab.audit']
48 | priority: 10
49 | deliveryMode: 2
50 | mandatory: false
51 | replyTo: user.signedup
52 | timestamp: true
53 | ack: true
54 | message:
55 | correlationId:
56 | location: $message.header#/correlation_id
57 | name: Temperature
58 | payload:
59 | $ref: '#/components/schemas/temperature'
60 | bindings:
61 | amqp:
62 | is: routingKey
63 | queue:
64 | name: temperatures
65 | x-prefetch-count: 100
66 | x-confirm: true
67 | exchange:
68 | name: lkab.iot.temperature
69 | type: topic
70 | durable: true
71 | autoDelete: false
72 | vhost: iot
73 | components:
74 | schemas:
75 | temperature:
76 | type: object
77 | properties:
78 | origin:
79 | type: string
80 | description: The origin of this temperature
81 | celcius:
82 | type: number
83 | description: Temperature measured in Celcius
84 | kelvin:
85 | type: number
86 | description: Temperature measured in Kelvin
87 | fahrenheit:
88 | type: number
89 | format: number
90 | description: Temperature measured in Fahrenheit
91 | created:
92 | type: string
93 | format: date-time
94 | description: Date and time when the tempreture was measured.
95 |
96 |
--------------------------------------------------------------------------------
/.github/workflows/add-good-first-issue-labels.yml:
--------------------------------------------------------------------------------
1 | # This workflow is centrally managed in https://github.com/asyncapi/.github/
2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo
3 |
4 | # Purpose of this workflow is to enable anyone to label issue with 'Good First Issue' and 'area/*' with a single command.
5 | name: Add 'Good First Issue' and 'area/*' labels # if proper comment added
6 |
7 | on:
8 | issue_comment:
9 | types:
10 | - created
11 |
12 | jobs:
13 | add-labels:
14 | if: ${{(!github.event.issue.pull_request && github.event.issue.state != 'closed' && github.actor != 'asyncapi-bot') && (contains(github.event.comment.body, '/good-first-issue') || contains(github.event.comment.body, '/gfi' ))}}
15 | runs-on: ubuntu-latest
16 | steps:
17 | - name: Add label
18 | uses: actions/github-script@v7
19 | with:
20 | github-token: ${{ secrets.GH_TOKEN }}
21 | script: |
22 | const areas = ['javascript', 'typescript', 'java' , 'go', 'docs', 'ci-cd', 'design'];
23 | const words = context.payload.comment.body.trim().split(" ");
24 | const areaIndex = words.findIndex((word)=> word === '/gfi' || word === '/good-first-issue') + 1
25 | let area = words[areaIndex];
26 | switch(area){
27 | case 'ts':
28 | area = 'typescript';
29 | break;
30 | case 'js':
31 | area = 'javascript';
32 | break;
33 | case 'markdown':
34 | area = 'docs';
35 | break;
36 | }
37 | if(!areas.includes(area)){
38 | const message = `Hey @${context.payload.sender.login}, your message doesn't follow the requirements, you can try \`/help\`.`
39 |
40 | await github.rest.issues.createComment({
41 | issue_number: context.issue.number,
42 | owner: context.repo.owner,
43 | repo: context.repo.repo,
44 | body: message
45 | })
46 | } else {
47 |
48 | // remove area if there is any before adding new labels.
49 | const currentLabels = (await github.rest.issues.listLabelsOnIssue({
50 | issue_number: context.issue.number,
51 | owner: context.repo.owner,
52 | repo: context.repo.repo,
53 | })).data.map(label => label.name);
54 |
55 | const shouldBeRemoved = currentLabels.filter(label => (label.startsWith('area/') && !label.endsWith(area)));
56 | shouldBeRemoved.forEach(label => {
57 | github.rest.issues.deleteLabel({
58 | owner: context.repo.owner,
59 | repo: context.repo.repo,
60 | name: label,
61 | });
62 | });
63 |
64 | // Add new labels.
65 | github.rest.issues.addLabels({
66 | issue_number: context.issue.number,
67 | owner: context.repo.owner,
68 | repo: context.repo.repo,
69 | labels: ['good first issue', `area/${area}`]
70 | });
71 | }
72 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
.NET C# RabbitMQ template
2 |
3 |
4 | This is a .NET C# RabbitMQ template for the AsyncAPI generator
5 |
6 |
7 |
8 |
9 | [](##Contributors-✨)
10 |
11 |
12 | This template is for generating a .NET C# wrapper for the RabbitMQ client based on your AsyncAPI document. The template uses the [RabbitMQ C# Client](https://rabbitmq.github.io/rabbitmq-dotnet-client/api/RabbitMQ.Client.html) library.
13 |
14 | Have you found a bug or have an idea for improvement? Feel free to contribute! See [the contribution guidelines](#Contributing) how to do so.
15 |
16 | ## Example usage
17 | Given any AsyncAPI file (`AsyncAPI.yml`) first generate the client with the [AsyncAPI generator](https://github.com/asyncapi/generator) such as
18 | ```bash
19 | ag .\asyncapi.yaml .\dotnet-rabbitmq-template\ -o .\output --force-write
20 | ```
21 |
22 | # How to use
23 | The generated output shall be seen a subscriber and/or publisher of message on/from a rabbit mq broker.
24 |
25 | ## Requirements
26 | * @asyncapi/generator < v2.0.0 > v1.1.1
27 |
28 | Install the generator through [npm or run it from docker official installer](https://github.com/asyncapi/generator#install).
29 |
30 | ## Template Parameters
31 | These are the available template parameters:
32 | |Parameter|Type|Description|
33 | |---|---|---|
34 | | namespace | String | Use this parameter to specify the namespace for the generated C# client `--param "namespace=Company.Services"`, defaults to `Demo`
35 | | user | String | Use this parameter to specify a user for for accessing the RabbitMq cluster `--param "user=username"`, defaults to `user`
36 | | password | String | Use this parameter to specify a password for for accessing the RabbitMq cluster `--param "password=password"`, defaults to `password`
37 |
38 | # Contributing
39 |
40 | Before contributing please read the [CONTRIBUTING](CONTRIBUTING.md) document.
41 |
42 |
43 | ## Contributors ✨
44 |
45 | Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
46 |
47 |
48 |
49 |
50 |
55 |
56 |
57 |
58 |
59 |
60 |
61 | This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!
--------------------------------------------------------------------------------
/.github/workflows/if-nodejs-version-bump.yml:
--------------------------------------------------------------------------------
1 | # This action is centrally managed in https://github.com/asyncapi/.github/
2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo
3 |
4 | # It does magic only if there is package.json file in the root of the project
5 | name: Version bump - if Node.js project
6 |
7 | on:
8 | release:
9 | types:
10 | - published
11 |
12 | jobs:
13 | version_bump:
14 | name: Generate assets and bump NodeJS
15 | runs-on: ubuntu-latest
16 | steps:
17 | - name: Checkout repository
18 | uses: actions/checkout@v2
19 | with:
20 | # target branch of release. More info https://docs.github.com/en/rest/reference/repos#releases
21 | # in case release is created from release branch then we need to checkout from given branch
22 | # if @semantic-release/github is used to publish, the minimum version is 7.2.0 for proper working
23 | ref: ${{ github.event.release.target_commitish }}
24 | - name: Check if Node.js project and has package.json
25 | id: packagejson
26 | run: test -e ./package.json && echo "::set-output name=exists::true" || echo "::set-output name=exists::false"
27 | - if: steps.packagejson.outputs.exists == 'true'
28 | name: Setup Node.js
29 | uses: actions/setup-node@v2
30 | with:
31 | node-version: 14
32 | cache: 'npm'
33 | cache-dependency-path: '**/package-lock.json'
34 | - if: steps.packagejson.outputs.exists == 'true'
35 | name: Install dependencies
36 | run: npm install
37 | - if: steps.packagejson.outputs.exists == 'true'
38 | name: Assets generation
39 | run: npm run generate:assets
40 | - if: steps.packagejson.outputs.exists == 'true'
41 | name: Bump version in package.json
42 | # There is no need to substract "v" from the tag as version script handles it
43 | # When adding "bump:version" script in package.json, make sure no tags are added by default (--no-git-tag-version) as they are already added by release workflow
44 | # When adding "bump:version" script in package.json, make sure --allow-same-version is set in case someone forgot and updated package.json manually and we want to avoide this action to fail and raise confusion
45 | run: VERSION=${{github.event.release.tag_name}} npm run bump:version
46 | - if: steps.packagejson.outputs.exists == 'true'
47 | name: Create Pull Request with updated asset files including package.json
48 | uses: peter-evans/create-pull-request@v3
49 | with:
50 | token: ${{ secrets.GH_TOKEN }}
51 | commit-message: 'chore(release): ${{github.event.release.tag_name}}'
52 | committer: asyncapi-bot
53 | author: asyncapi-bot
54 | title: 'chore(release): ${{github.event.release.tag_name}}'
55 | body: 'Version bump in package.json for release [${{github.event.release.tag_name}}](${{github.event.release.html_url}})'
56 | branch: version-bump/${{github.event.release.tag_name}}
57 | - if: failure() # Only, on failure, send a message on the 94_bot-failing-ci slack channel
58 | name: Report workflow run status to Slack
59 | uses: 8398a7/action-slack@v3
60 | with:
61 | status: ${{ job.status }}
62 | fields: repo,action,workflow
63 | text: 'Unable to bump the version in package.json after the release'
64 | env:
65 | SLACK_WEBHOOK_URL: ${{ secrets.SLACK_CI_FAIL_NOTIFY }}
--------------------------------------------------------------------------------
/test/producers.test.spec.js:
--------------------------------------------------------------------------------
1 | import { render } from '@asyncapi/generator-react-sdk';
2 | import AsyncAPIDocument from '@asyncapi/parser/lib/models/asyncapi';
3 | import { Publishers } from '../components/Publishers';
4 | import { cleanString, getChannels } from '../utils/common';
5 |
6 | describe('Producer component tests', () => {
7 | it('should handle empty specification', () => {
8 | const asyncapi = new AsyncAPIDocument({
9 | asyncapi: '2.2.0',
10 | defaultContentType: 'application/json',
11 | });
12 |
13 | const expected = '';
14 |
15 | const result = render();
16 |
17 | expect(cleanString(result)).toEqual(cleanString(expected));
18 | });
19 |
20 | it('should render producer implementation', () => {
21 | const asyncapi = new AsyncAPIDocument({
22 | asyncapi: '2.2.0',
23 | defaultContentType: 'application/json',
24 | channels: {
25 | '{sensorId}.temperature': {
26 | publish: {
27 | operationId: 'onSpecificSensorTemperatureChanged',
28 | description: 'Publish a temperature change from a specific sensor.',
29 | bindings: {
30 | amqp: {
31 | expiration: 100000,
32 | userId: 'guest',
33 | cc: ['lkab.user.logs'],
34 | bcc: ['lkab.audit'],
35 | priority: 10,
36 | deliveryMode: 2,
37 | mandatory: false,
38 | replyTo: 'user.signedup',
39 | timestamp: true,
40 | ack: true,
41 | },
42 | },
43 | message: {
44 | payload: {
45 | id: 'temperature',
46 | type: 'object',
47 | additionalProperties: false,
48 | properties: {
49 | celsius: { type: 'number', format: 'decimal' },
50 | kelvin: { type: 'number', format: 'decimal' },
51 | fahrenheit: { type: 'number', format: 'decimal' },
52 | origin: { type: ['null', 'string'] },
53 | created: { type: 'string', format: 'date-time' },
54 | },
55 | },
56 | name: 'temperature',
57 | },
58 | },
59 | parameters: {
60 | sensorId: {
61 | 'x-example': 'SENSOR-001',
62 | description: 'Id of the temperature sensor.',
63 | schema: { type: 'string' },
64 | },
65 | },
66 | bindings: {
67 | amqp: {
68 | is: 'routingKey',
69 | exchange: {
70 | 'x-alternate-exchange': 'lkab.iot.other',
71 | name: 'lkab.iot.temperature',
72 | type: 'topic',
73 | durable: true,
74 | autoDelete: false,
75 | },
76 | },
77 | },
78 | },
79 | },
80 | });
81 |
82 | const expected = `
83 | // Code for the publisher: Send message on custom events, below is a timing example.
84 | // A real world example would probably read temeratures from some kind of I/O temperature sensor.
85 | /*
86 | var rnd = new Random((int) DateTime.Now.Ticks);
87 | while (!stoppingToken.IsCancellationRequested)
88 | {
89 | var message = new Temperature();
90 | _amqpService.OnSpecificSensorTemperatureChanged(message);
91 | await Task.Delay(rnd.Next(500, 3000), stoppingToken);
92 | }
93 | */`;
94 |
95 | const result = render();
96 |
97 | expect(cleanString(result)).toEqual(cleanString(expected));
98 | });
99 | });
100 |
--------------------------------------------------------------------------------
/.github/workflows/if-nodejs-pr-testing.yml:
--------------------------------------------------------------------------------
1 | # This action is centrally managed in https://github.com/asyncapi/.github/
2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo
3 |
4 | # It does magic only if there is package.json file in the root of the project
5 | name: PR testing - if Node project
6 |
7 | on:
8 | pull_request:
9 | types: [opened, reopened, synchronize, ready_for_review]
10 |
11 | jobs:
12 | test-nodejs-pr:
13 | name: Test NodeJS PR - ${{ matrix.os }}
14 | runs-on: ${{ matrix.os }}
15 | strategy:
16 | matrix:
17 | os: [ubuntu-latest, macos-latest, windows-latest]
18 | steps:
19 | - if: >
20 | !github.event.pull_request.draft && !(
21 | (github.actor == 'asyncapi-bot' && (
22 | startsWith(github.event.pull_request.title, 'ci: update of files from global .github repo') ||
23 | startsWith(github.event.pull_request.title, 'chore(release):')
24 | )) ||
25 | (github.actor == 'asyncapi-bot-eve' && (
26 | startsWith(github.event.pull_request.title, 'ci: update of files from global .github repo') ||
27 | startsWith(github.event.pull_request.title, 'chore(release):')
28 | )) ||
29 | (github.actor == 'allcontributors[bot]' &&
30 | startsWith(github.event.pull_request.title, 'docs: add')
31 | )
32 | )
33 | id: should_run
34 | name: Should Run
35 | run: echo "shouldrun=true" >> $GITHUB_OUTPUT
36 | shell: bash
37 | - if: steps.should_run.outputs.shouldrun == 'true'
38 | name: Set git to use LF #to once and for all finish neverending fight between Unix and Windows
39 | run: |
40 | git config --global core.autocrlf false
41 | git config --global core.eol lf
42 | shell: bash
43 | - if: steps.should_run.outputs.shouldrun == 'true'
44 | name: Checkout repository
45 | uses: actions/checkout@v4
46 | - if: steps.should_run.outputs.shouldrun == 'true'
47 | name: Check if Node.js project and has package.json
48 | id: packagejson
49 | run: test -e ./package.json && echo "exists=true" >> $GITHUB_OUTPUT || echo "exists=false" >> $GITHUB_OUTPUT
50 | shell: bash
51 | - if: steps.packagejson.outputs.exists == 'true'
52 | name: Check package-lock version
53 | # This workflow is from our own org repo and safe to reference by 'master'.
54 | uses: asyncapi/.github/.github/actions/get-node-version-from-package-lock@master # //NOSONAR
55 | id: lockversion
56 | - if: steps.packagejson.outputs.exists == 'true'
57 | name: Setup Node.js
58 | uses: actions/setup-node@v4
59 | with:
60 | node-version: "${{ steps.lockversion.outputs.version }}"
61 | - if: steps.lockversion.outputs.version == '18' && matrix.os == 'windows-latest'
62 | #npm cli 10 is buggy because of some cache issue
63 | name: Install npm cli 8
64 | shell: bash
65 | run: npm install -g npm@8.19.4
66 | - if: steps.packagejson.outputs.exists == 'true'
67 | name: Install dependencies
68 | shell: bash
69 | run: npm ci
70 | - if: steps.packagejson.outputs.exists == 'true'
71 | name: Test
72 | run: npm test --if-present
73 | - if: steps.packagejson.outputs.exists == 'true' && matrix.os == 'ubuntu-latest'
74 | #linting should run just one and not on all possible operating systems
75 | name: Run linter
76 | run: npm run lint --if-present
77 | - if: steps.packagejson.outputs.exists == 'true'
78 | name: Run release assets generation to make sure PR does not break it
79 | shell: bash
80 | run: npm run generate:assets --if-present
81 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@asyncapi/dotnet-rabbitmq-template",
3 | "version": "1.0.0",
4 | "description": "Template package for AsyncAPI code generation",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "jest --coverage",
8 | "get-version": "echo $npm_package_version",
9 | "gen-readme-toc": "markdown-toc -i README.md",
10 | "lint": "eslint --max-warnings 0 --fix --config .eslintrc .",
11 | "release": "semantic-release",
12 | "bump:version": "npm --no-git-tag-version --allow-same-version version $VERSION",
13 | "generate:assets": "",
14 | "generate:examples": ""
15 | },
16 | "keywords": [
17 | "asyncapi",
18 | "generator",
19 | "template",
20 | "dotnet",
21 | "rabbitmq"
22 | ],
23 | "author": "Peter Wikström (https://github.com/mr-nuno)",
24 | "license": "Apache-2.0",
25 | "publishConfig": {
26 | "access": "public"
27 | },
28 | "dependencies": {
29 | "@asyncapi/generator-filters": "^1.1.0",
30 | "@asyncapi/generator-hooks": "^0.1.0",
31 | "@asyncapi/modelina": "^0.59.4",
32 | "lodash": "^4.17.15"
33 | },
34 | "devDependencies": {
35 | "@asyncapi/generator": "^1.9.18",
36 | "@asyncapi/parser": "^1.15.1",
37 | "@babel/preset-env": "^7.15.8",
38 | "@babel/preset-react": "^7.14.5",
39 | "@semantic-release/commit-analyzer": "^8.0.1",
40 | "@semantic-release/github": "7.2.3",
41 | "@semantic-release/npm": "^7.0.5",
42 | "@semantic-release/release-notes-generator": "^9.0.1",
43 | "all-contributors-cli": "^6.19.0",
44 | "conventional-changelog-conventionalcommits": "^4.4.0",
45 | "eslint": "^7.17.0",
46 | "eslint-plugin-jest": "^23.20.0",
47 | "eslint-plugin-react": "^7.22.0",
48 | "eslint-plugin-security": "^1.4.0",
49 | "eslint-plugin-sonarjs": "^0.5.0",
50 | "jest": "^26.4.2",
51 | "jest-esm-transformer": "^1.0.0",
52 | "markdown-toc": "^1.2.0",
53 | "rimraf": "^3.0.2",
54 | "semantic-release": "19.0.3"
55 | },
56 | "generator": {
57 | "renderer": "react",
58 | "parameters": {
59 | "supportedProtocols": [
60 | "amqp"
61 | ],
62 | "asyncapiFileDir": {
63 | "description": "Custom location of the AsyncAPI file that you provided as an input in generation. By default it is located in the root of the output directory"
64 | },
65 | "namespace": {
66 | "description": "Name of the package, this is used as the base namespace for all classes within gen code. Useful for whitelabel as well ;)",
67 | "default": "Demo"
68 | },
69 | "user": {
70 | "description": "The user to the AMQP broker",
71 | "default": "user"
72 | },
73 | "password": {
74 | "description": "The password to the AMQP broker",
75 | "default": "password"
76 | }
77 | },
78 | "filters": [
79 | "@asyncapi/generator-filters"
80 | ],
81 | "generator": ">=1.1.0 <2.0.0"
82 | },
83 | "babel": {
84 | "presets": [
85 | "@babel/preset-env",
86 | [
87 | "@babel/preset-react",
88 | {
89 | "runtime": "automatic"
90 | }
91 | ]
92 | ]
93 | },
94 | "jest": {
95 | "moduleFileExtensions": [
96 | "js",
97 | "json",
98 | "jsx"
99 | ]
100 | },
101 | "release": {
102 | "branches": [
103 | "master"
104 | ],
105 | "plugins": [
106 | [
107 | "@semantic-release/commit-analyzer",
108 | {
109 | "preset": "conventionalcommits"
110 | }
111 | ],
112 | [
113 | "@semantic-release/release-notes-generator",
114 | {
115 | "preset": "conventionalcommits"
116 | }
117 | ],
118 | "@semantic-release/npm",
119 | "@semantic-release/github"
120 | ]
121 | }
122 | }
123 |
--------------------------------------------------------------------------------
/.github/workflows/help-command.yml:
--------------------------------------------------------------------------------
1 | # This workflow is centrally managed in https://github.com/asyncapi/.github/
2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo
3 |
4 | name: Create help comment
5 |
6 | on:
7 | issue_comment:
8 | types:
9 | - created
10 |
11 | jobs:
12 | create_help_comment_pr:
13 | if: ${{ github.event.issue.pull_request && startsWith(github.event.comment.body, '/help') && github.actor != 'asyncapi-bot' }}
14 | runs-on: ubuntu-latest
15 | steps:
16 | - name: Add comment to PR
17 | uses: actions/github-script@v7
18 | env:
19 | ACTOR: ${{ github.actor }}
20 | with:
21 | github-token: ${{ secrets.GH_TOKEN }}
22 | script: |
23 | //Yes to add comment to PR the same endpoint is use that we use to create a comment in issue
24 | //For more details http://developer.github.com/v3/issues/comments/
25 | //Also proved by this action https://github.com/actions-ecosystem/action-create-comment/blob/main/src/main.ts
26 | github.rest.issues.createComment({
27 | issue_number: context.issue.number,
28 | owner: context.repo.owner,
29 | repo: context.repo.repo,
30 | body: `Hello, @${process.env.ACTOR}! 👋🏼
31 |
32 | I'm 🧞🧞🧞 Genie 🧞🧞🧞 from the magic lamp. Looks like somebody needs a hand!
33 |
34 | At the moment the following comments are supported in pull requests:
35 |
36 | - \`/please-take-a-look\` or \`/ptal\` - This comment will add a comment to the PR asking for attention from the reviewrs who have not reviewed the PR yet.
37 | - \`/ready-to-merge\` or \`/rtm\` - This comment will trigger automerge of PR in case all required checks are green, approvals in place and do-not-merge label is not added
38 | - \`/do-not-merge\` or \`/dnm\` - This comment will block automerging even if all conditions are met and ready-to-merge label is added
39 | - \`/autoupdate\` or \`/au\` - This comment will add \`autoupdate\` label to the PR and keeps your PR up-to-date to the target branch's future changes. Unless there is a merge conflict or it is a draft PR. (Currently only works for upstream branches.)
40 | - \`/update\` or \`/u\` - This comment will update the PR with the latest changes from the target branch. Unless there is a merge conflict or it is a draft PR. NOTE: this only updates the PR once, so if you need to update again, you need to call the command again.`
41 | })
42 |
43 | create_help_comment_issue:
44 | if: ${{ !github.event.issue.pull_request && startsWith(github.event.comment.body, '/help') && github.actor != 'asyncapi-bot' }}
45 | runs-on: ubuntu-latest
46 | steps:
47 | - name: Add comment to Issue
48 | uses: actions/github-script@v7
49 | env:
50 | ACTOR: ${{ github.actor }}
51 | with:
52 | github-token: ${{ secrets.GH_TOKEN }}
53 | script: |
54 | github.rest.issues.createComment({
55 | issue_number: context.issue.number,
56 | owner: context.repo.owner,
57 | repo: context.repo.repo,
58 | body: `Hello, @${process.env.ACTOR}! 👋🏼
59 |
60 | I'm 🧞🧞🧞 Genie 🧞🧞🧞 from the magic lamp. Looks like somebody needs a hand!
61 |
62 | At the moment the following comments are supported in issues:
63 |
64 | - \`/good-first-issue {js | ts | java | go | docs | design | ci-cd}\` or \`/gfi {js | ts | java | go | docs | design | ci-cd}\` - label an issue as a \`good first issue\`.
65 | example: \`/gfi js\` or \`/good-first-issue ci-cd\`
66 | - \`/transfer-issue {repo-name}\` or \`/ti {repo-name}\` - transfer issue from the source repository to the other repository passed by the user. example: \`/ti cli\` or \`/transfer-issue cli\`.`
67 | })
--------------------------------------------------------------------------------
/components/templates/channelpool.js:
--------------------------------------------------------------------------------
1 | import { getChannels, toPascalCase } from '../../utils/common';
2 |
3 | const template = (asyncapi, params) => {
4 | const publishers = getChannels(asyncapi).filter(
5 | (channel) => channel.isPublish
6 | );
7 | const consumers = getChannels(asyncapi).filter(
8 | (channel) => !channel.isPublish
9 | );
10 |
11 | return `using System;
12 | using System.Collections.Generic;
13 | using ${params.namespace}.Services.Interfaces;
14 | using RabbitMQ.Client;
15 |
16 | namespace ${params.namespace}.Services;
17 |
18 | ///
19 | /// A channel pool for all channels defined in the async api specification
20 | ///
21 | public class ChannelPool : IChannelPool
22 | {
23 | private class Channel : IDisposable
24 | {
25 | ///
26 | /// The confirm mode for the channel
27 | ///
28 | public bool Confirm { get; init; }
29 |
30 | ///
31 | /// The prefetch count for the channel
32 | ///
33 | public ushort PrefetchCount { get; init; }
34 |
35 | ///
36 | /// The underlying amqp model/channel
37 | ///
38 | public IModel Model { get; init; }
39 |
40 | public void Dispose()
41 | {
42 | Model?.Close();
43 | Model?.Dispose();
44 | }
45 | }
46 |
47 | private readonly IConnection _connection;
48 | private readonly IDictionary _channels = new Dictionary();
49 |
50 | private ChannelPool(IConnection connection)
51 | {
52 | _connection = connection;
53 |
54 | // creating producer channels
55 | ${publishers.map(
56 | (publisher) => `_channels.Add(
57 | "${toPascalCase(publisher.operationId)}",
58 | CreateChannel(connection));`
59 | )}
60 |
61 | // creating consumer channels
62 | ${consumers.map(
63 | (consumer) => `_channels.Add(
64 | "${toPascalCase(consumer.operationId)}",
65 | CreateChannel(
66 | connection,
67 | ${consumer.prefetchCount},
68 | ${consumer.confirm}));`
69 | )}
70 |
71 | }
72 |
73 | public static IChannelPool Create(IConnection connection)
74 | {
75 | return new ChannelPool(connection);
76 | }
77 |
78 | public IModel GetChannel(string operationId)
79 | {
80 | // check for channel
81 | if (!_channels.TryGetValue(operationId, out var channel))
82 | {
83 | throw new KeyNotFoundException($"No channel found for {operationId}");
84 | }
85 |
86 | if (!channel.Model.IsClosed)
87 | {
88 | return channel.Model;
89 | }
90 |
91 | // recreate channel if it is closed
92 | _channels[operationId] = CreateChannel(
93 | _connection,
94 | channel.PrefetchCount, // prefetch from x-prefetch-count on channel binding
95 | channel.Confirm); // confirm from confirm on operation binding
96 |
97 | return _channels[operationId].Model;
98 | }
99 |
100 | private Channel CreateChannel(
101 | IConnection connection,
102 | ushort prefetchCount = 100,
103 | bool confirm = false)
104 | {
105 | var model = connection.CreateModel();
106 |
107 | if (confirm)
108 | {
109 | model.ConfirmSelect();
110 | }
111 |
112 | model.BasicQos(0, prefetchCount, false);
113 |
114 | return new Channel
115 | {
116 | PrefetchCount = prefetchCount,
117 | Confirm = confirm,
118 | Model = model
119 | };
120 | }
121 |
122 | public void Dispose()
123 | {
124 | foreach (var (_, channel) in _channels)
125 | {
126 | channel?.Dispose();
127 | }
128 | }
129 | }`;
130 | };
131 |
132 | export function ChannelPool({ asyncapi, params }) {
133 | if (!asyncapi.hasChannels()) {
134 | return null;
135 | }
136 |
137 | return template(asyncapi, params);
138 | }
139 |
--------------------------------------------------------------------------------
/test/amqpservice.test.spec.js:
--------------------------------------------------------------------------------
1 | import { render } from '@asyncapi/generator-react-sdk';
2 | import AsyncAPIDocument from '@asyncapi/parser/lib/models/asyncapi';
3 | import { AmqpService } from '../components/templates/amqpservice';
4 | import { cleanString } from '../utils/common';
5 |
6 | describe('AMQP service component', () => {
7 | it('should handle empty specification', () => {
8 | const asyncapi = new AsyncAPIDocument({
9 | asyncapi: '2.2.0',
10 | defaultContentType: 'application/json',
11 | });
12 |
13 | const expected = '';
14 |
15 | const result = render();
16 |
17 | expect(cleanString(result)).toEqual(cleanString(expected));
18 | });
19 |
20 | it('should render a amqpservice', () => {
21 | const asyncapi = new AsyncAPIDocument({
22 | asyncapi: '2.2.0',
23 | info: {
24 | title: 'Test',
25 | version: '1.0.0',
26 | },
27 | defaultContentType: 'application/json',
28 | channels: {
29 | '{sensorId}.temperature': {
30 | publish: {
31 | operationId: 'onSpecificSensorTemperatureReceived',
32 | description:
33 | 'Subscribe to a temperature change from a specific sensor.',
34 | bindings: {
35 | amqp: {
36 | expiration: 100000,
37 | userId: 'guest',
38 | cc: ['lkab.user.logs'],
39 | bcc: ['lkab.audit'],
40 | priority: 10,
41 | deliveryMode: 2,
42 | mandatory: false,
43 | replyTo: 'user.signedup',
44 | timestamp: true,
45 | ack: true,
46 | },
47 | },
48 | message: {
49 | payload: {
50 | id: 'temperature',
51 | type: 'object',
52 | additionalProperties: false,
53 | properties: {
54 | celsius: { type: 'number', format: 'decimal' },
55 | kelvin: { type: 'number', format: 'decimal' },
56 | fahrenheit: { type: 'number', format: 'decimal' },
57 | origin: { type: ['null', 'string'] },
58 | created: { type: 'string', format: 'date-time' },
59 | },
60 | },
61 | name: 'temperature',
62 | },
63 | },
64 | subscribe: {
65 | operationId: 'onSpecificSensorTemperatureReceived',
66 | description:
67 | 'Subscribe to a temperature change from a specific sensor.',
68 | message: {
69 | payload: {
70 | id: 'temperature',
71 | type: 'object',
72 | additionalProperties: false,
73 | properties: {
74 | celsius: { type: 'number', format: 'decimal' },
75 | kelvin: { type: 'number', format: 'decimal' },
76 | fahrenheit: { type: 'number', format: 'decimal' },
77 | origin: { type: ['null', 'string'] },
78 | created: { type: 'string', format: 'date-time' },
79 | },
80 | },
81 | name: 'temperature',
82 | },
83 | },
84 | parameters: {
85 | sensorId: {
86 | 'x-example': 'SENSOR-001',
87 | description: 'Id of the temperature sensor.',
88 | schema: { type: 'string' },
89 | },
90 | },
91 | bindings: {
92 | amqp: {
93 | is: 'routingKey',
94 | exchange: { name: 'temperature', type: 'topic', vhost: '/' },
95 | queue: { name: 'temperatures' },
96 | },
97 | },
98 | },
99 | },
100 | });
101 |
102 | const result = render(
103 |
107 | );
108 |
109 | expect(cleanString(result)).toContain('var queue = "temperatures";');
110 | expect(cleanString(result)).toContain(
111 | 'void OnSpecificSensorTemperatureReceived(Temperature message)'
112 | );
113 | });
114 | });
115 |
--------------------------------------------------------------------------------
/.github/workflows/issues-prs-notifications.yml:
--------------------------------------------------------------------------------
1 | # This action is centrally managed in https://github.com/asyncapi/.github/
2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo
3 |
4 | # This action notifies community on slack whenever there is a new issue, PR or discussion started in given repository
5 | name: Notify slack
6 |
7 | on:
8 | issues:
9 | types: [opened, reopened]
10 |
11 | pull_request_target:
12 | types: [opened, reopened, ready_for_review]
13 |
14 | discussion:
15 | types: [created]
16 |
17 | jobs:
18 | issue:
19 | if: github.event_name == 'issues' && github.actor != 'asyncapi-bot' && github.actor != 'dependabot[bot]' && github.actor != 'dependabot-preview[bot]'
20 | name: Notify slack on every new issue
21 | runs-on: ubuntu-latest
22 | steps:
23 | - name: Convert markdown to slack markdown for issue
24 | # This workflow is from our own org repo and safe to reference by 'master'.
25 | uses: asyncapi/.github/.github/actions/slackify-markdown@master # //NOSONAR
26 | id: issuemarkdown
27 | env:
28 | ISSUE_TITLE: ${{github.event.issue.title}}
29 | ISSUE_URL: ${{github.event.issue.html_url}}
30 | ISSUE_BODY: ${{github.event.issue.body}}
31 | with:
32 | markdown: "[${{ env.ISSUE_TITLE }}](${{ env.ISSUE_URL }}) \n ${{ env.ISSUE_BODY }}"
33 | - name: Send info about issue
34 | uses: rtCamp/action-slack-notify@c33737706dea87cd7784c687dadc9adf1be59990 # Using v2.3.2
35 | env:
36 | SLACK_WEBHOOK: ${{secrets.SLACK_GITHUB_NEWISSUEPR}}
37 | SLACK_TITLE: 🐛 New Issue in ${{github.repository}} 🐛
38 | SLACK_MESSAGE: ${{steps.issuemarkdown.outputs.text}}
39 | MSG_MINIMAL: true
40 |
41 | pull_request:
42 | if: github.event_name == 'pull_request_target' && github.actor != 'asyncapi-bot' && github.actor != 'dependabot[bot]' && github.actor != 'dependabot-preview[bot]'
43 | name: Notify slack on every new pull request
44 | runs-on: ubuntu-latest
45 | steps:
46 | - name: Convert markdown to slack markdown for pull request
47 | # This workflow is from our own org repo and safe to reference by 'master'.
48 | uses: asyncapi/.github/.github/actions/slackify-markdown@master # //NOSONAR
49 | id: prmarkdown
50 | env:
51 | PR_TITLE: ${{github.event.pull_request.title}}
52 | PR_URL: ${{github.event.pull_request.html_url}}
53 | PR_BODY: ${{github.event.pull_request.body}}
54 | with:
55 | markdown: "[${{ env.PR_TITLE }}](${{ env.PR_URL }}) \n ${{ env.PR_BODY }}"
56 | - name: Send info about pull request
57 | uses: rtCamp/action-slack-notify@c33737706dea87cd7784c687dadc9adf1be59990 # Using v2.3.2
58 | env:
59 | SLACK_WEBHOOK: ${{secrets.SLACK_GITHUB_NEWISSUEPR}}
60 | SLACK_TITLE: 💪 New Pull Request in ${{github.repository}} 💪
61 | SLACK_MESSAGE: ${{steps.prmarkdown.outputs.text}}
62 | MSG_MINIMAL: true
63 |
64 | discussion:
65 | if: github.event_name == 'discussion' && github.actor != 'asyncapi-bot' && github.actor != 'dependabot[bot]' && github.actor != 'dependabot-preview[bot]'
66 | name: Notify slack on every new pull request
67 | runs-on: ubuntu-latest
68 | steps:
69 | - name: Convert markdown to slack markdown for pull request
70 | # This workflow is from our own org repo and safe to reference by 'master'.
71 | uses: asyncapi/.github/.github/actions/slackify-markdown@master # //NOSONAR
72 | id: discussionmarkdown
73 | env:
74 | DISCUSSION_TITLE: ${{github.event.discussion.title}}
75 | DISCUSSION_URL: ${{github.event.discussion.html_url}}
76 | DISCUSSION_BODY: ${{github.event.discussion.body}}
77 | with:
78 | markdown: "[${{ env.DISCUSSION_TITLE }}](${{ env.DISCUSSION_URL }}) \n ${{ env.DISCUSSION_BODY }}"
79 | - name: Send info about pull request
80 | uses: rtCamp/action-slack-notify@c33737706dea87cd7784c687dadc9adf1be59990 # Using v2.3.2
81 | env:
82 | SLACK_WEBHOOK: ${{secrets.SLACK_GITHUB_NEWISSUEPR}}
83 | SLACK_TITLE: 💬 New Discussion in ${{github.repository}} 💬
84 | SLACK_MESSAGE: ${{steps.discussionmarkdown.outputs.text}}
85 | MSG_MINIMAL: true
86 |
--------------------------------------------------------------------------------
/.github/workflows/automerge-for-humans-merging.yml:
--------------------------------------------------------------------------------
1 | # This workflow is centrally managed in https://github.com/asyncapi/.github/
2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo
3 |
4 | # Purpose of this workflow is to allow people to merge PR without a need of maintainer doing it. If all checks are in place (including maintainers approval) - JUST MERGE IT!
5 | name: Automerge For Humans
6 |
7 | on:
8 | pull_request_target:
9 | types:
10 | - labeled
11 | - unlabeled
12 | - synchronize
13 | - opened
14 | - edited
15 | - ready_for_review
16 | - reopened
17 | - unlocked
18 |
19 | jobs:
20 | automerge-for-humans:
21 | # it runs only if PR actor is not a bot, at least not a bot that we know
22 | if: |
23 | github.event.pull_request.draft == false &&
24 | (github.event.pull_request.user.login != 'asyncapi-bot' ||
25 | github.event.pull_request.user.login != 'dependabot[bot]' ||
26 | github.event.pull_request.user.login != 'dependabot-preview[bot]')
27 | runs-on: ubuntu-latest
28 | steps:
29 | - name: Get PR authors
30 | id: authors
31 | uses: actions/github-script@v7
32 | with:
33 | script: |
34 | // Get paginated list of all commits in the PR
35 | try {
36 | const commitOpts = github.rest.pulls.listCommits.endpoint.merge({
37 | owner: context.repo.owner,
38 | repo: context.repo.repo,
39 | pull_number: context.issue.number
40 | });
41 |
42 | const commits = await github.paginate(commitOpts);
43 |
44 | if (commits.length === 0) {
45 | core.setFailed('No commits found in the PR');
46 | return '';
47 | }
48 |
49 | // Get unique authors from the commits list
50 | const authors = commits.reduce((acc, commit) => {
51 | const username = commit.author?.login || commit.commit.author?.name;
52 | if (username && !acc[username]) {
53 | acc[username] = {
54 | name: commit.commit.author?.name,
55 | email: commit.commit.author?.email,
56 | }
57 | }
58 |
59 | return acc;
60 | }, {});
61 |
62 | return authors;
63 | } catch (error) {
64 | core.setFailed(error.message);
65 | return [];
66 | }
67 |
68 | - name: Create commit message
69 | id: create-commit-message
70 | uses: actions/github-script@v7
71 | with:
72 | script: |
73 | const authors = ${{ steps.authors.outputs.result }};
74 |
75 | if (Object.keys(authors).length === 0) {
76 | core.setFailed('No authors found in the PR');
77 | return '';
78 | }
79 |
80 | // Create a string of the form "Co-authored-by: Name "
81 | // ref: https://docs.github.com/en/pull-requests/committing-changes-to-your-project/creating-and-editing-commits/creating-a-commit-with-multiple-authors
82 | const coAuthors = Object.values(authors).map(author => {
83 | return `Co-authored-by: ${author.name} <${author.email}>`;
84 | }).join('\n');
85 |
86 | core.debug(coAuthors);;
87 |
88 | return coAuthors;
89 |
90 | - name: Automerge PR
91 | uses: pascalgn/automerge-action@22948e0bc22f0aa673800da838595a3e7347e584 #v0.15.6 https://github.com/pascalgn/automerge-action/releases/tag/v0.15.6
92 | env:
93 | GITHUB_TOKEN: "${{ secrets.GH_TOKEN }}"
94 | MERGE_LABELS: "!do-not-merge,ready-to-merge"
95 | MERGE_METHOD: "squash"
96 | # Using the output of the previous step (`Co-authored-by: ...` lines) as commit description.
97 | # Important to keep 2 empty lines as https://docs.github.com/en/pull-requests/committing-changes-to-your-project/creating-and-editing-commits/creating-a-commit-with-multiple-authors#creating-co-authored-commits-on-the-command-line mentions
98 | MERGE_COMMIT_MESSAGE: "{pullRequest.title} (#{pullRequest.number})\n\n\n${{ fromJSON(steps.create-commit-message.outputs.result) }}"
99 | MERGE_RETRIES: "20"
100 | MERGE_RETRY_SLEEP: "30000"
101 |
--------------------------------------------------------------------------------
/.github/workflows/welcome-first-time-contrib.yml:
--------------------------------------------------------------------------------
1 | # This action is centrally managed in https://github.com/asyncapi/.github/
2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo
3 |
4 | name: Welcome first time contributors
5 |
6 | on:
7 | pull_request_target:
8 | types:
9 | - opened
10 | issues:
11 | types:
12 | - opened
13 |
14 | jobs:
15 | welcome:
16 | name: Post welcome message
17 | if: ${{ !contains(fromJson('["asyncapi-bot", "dependabot[bot]", "dependabot-preview[bot]", "allcontributors[bot]"]'), github.actor) }}
18 | runs-on: ubuntu-latest
19 | steps:
20 | - uses: actions/github-script@v7
21 | with:
22 | github-token: ${{ secrets.GITHUB_TOKEN }}
23 | script: |
24 | const issueMessage = `Welcome to AsyncAPI. Thanks a lot for reporting your first issue. Please check out our [contributors guide](https://github.com/asyncapi/community/blob/master/CONTRIBUTING.md) and the instructions about a [basic recommended setup](https://github.com/asyncapi/community/blob/master/git-workflow.md) useful for opening a pull request.
Keep in mind there are also other channels you can use to interact with AsyncAPI community. For more details check out [this issue](https://github.com/asyncapi/asyncapi/issues/115).`;
25 | const prMessage = `Welcome to AsyncAPI. Thanks a lot for creating your first pull request. Please check out our [contributors guide](https://github.com/asyncapi/community/blob/master/CONTRIBUTING.md) useful for opening a pull request.
Keep in mind there are also other channels you can use to interact with AsyncAPI community. For more details check out [this issue](https://github.com/asyncapi/asyncapi/issues/115).`;
26 | if (!issueMessage && !prMessage) {
27 | throw new Error('Action must have at least one of issue-message or pr-message set');
28 | }
29 | const isIssue = !!context.payload.issue;
30 | let isFirstContribution;
31 | if (isIssue) {
32 | const query = `query($owner:String!, $name:String!, $contributer:String!) {
33 | repository(owner:$owner, name:$name){
34 | issues(first: 1, filterBy: {createdBy:$contributer}){
35 | totalCount
36 | }
37 | }
38 | }`;
39 | const variables = {
40 | owner: context.repo.owner,
41 | name: context.repo.repo,
42 | contributer: context.payload.sender.login
43 | };
44 | const { repository: { issues: { totalCount } } } = await github.graphql(query, variables);
45 | isFirstContribution = totalCount === 1;
46 | } else {
47 | const query = `query($qstr: String!) {
48 | search(query: $qstr, type: ISSUE, first: 1) {
49 | issueCount
50 | }
51 | }`;
52 | const variables = {
53 | "qstr": `repo:${context.repo.owner}/${context.repo.repo} type:pr author:${context.payload.sender.login}`,
54 | };
55 | const { search: { issueCount } } = await github.graphql(query, variables);
56 | isFirstContribution = issueCount === 1;
57 | }
58 |
59 | if (!isFirstContribution) {
60 | console.log(`Not the users first contribution.`);
61 | return;
62 | }
63 | const message = isIssue ? issueMessage : prMessage;
64 | // Add a comment to the appropriate place
65 | if (isIssue) {
66 | const issueNumber = context.payload.issue.number;
67 | console.log(`Adding message: ${message} to issue #${issueNumber}`);
68 | await github.rest.issues.createComment({
69 | owner: context.payload.repository.owner.login,
70 | repo: context.payload.repository.name,
71 | issue_number: issueNumber,
72 | body: message
73 | });
74 | }
75 | else {
76 | const pullNumber = context.payload.pull_request.number;
77 | console.log(`Adding message: ${message} to pull request #${pullNumber}`);
78 | await github.rest.pulls.createReview({
79 | owner: context.payload.repository.owner.login,
80 | repo: context.payload.repository.name,
81 | pull_number: pullNumber,
82 | body: message,
83 | event: 'COMMENT'
84 | });
85 | }
86 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing to AsyncAPI
2 | We love your input! We want to make contributing to this project as easy and transparent as possible.
3 |
4 | ## Contribution recogniton
5 |
6 | We use [All Contributors](https://allcontributors.org/docs/en/specification) specification to handle recognitions. For more details read [this](https://www.asyncapi.com/docs/community/010-contribution-guidelines/recognize-contributors#main-content) document.
7 |
8 |
9 |
10 |
11 | ## Summary of the contribution flow
12 |
13 | The following is a summary of the ideal contribution flow. Please, note that Pull Requests can also be rejected by the maintainers when appropriate.
14 |
15 | ```
16 | ┌───────────────────────┐
17 | │ │
18 | │ Open an issue │
19 | │ (a bug report or a │
20 | │ feature request) │
21 | │ │
22 | └───────────────────────┘
23 | ⇩
24 | ┌───────────────────────┐
25 | │ │
26 | │ Open a Pull Request │
27 | │ (only after issue │
28 | │ is approved) │
29 | │ │
30 | └───────────────────────┘
31 | ⇩
32 | ┌───────────────────────┐
33 | │ │
34 | │ Your changes will │
35 | │ be merged and │
36 | │ published on the next │
37 | │ release │
38 | │ │
39 | └───────────────────────┘
40 | ```
41 |
42 | ## Code of Conduct
43 | AsyncAPI has adopted a Code of Conduct that we expect project participants to adhere to. Please [read the full text](./CODE_OF_CONDUCT.md) so that you can understand what sort of behaviour is expected.
44 |
45 | ## Our Development Process
46 | We use Github to host code, to track issues and feature requests, as well as accept pull requests.
47 |
48 | ## Issues
49 | [Open an issue](https://github.com/asyncapi/asyncapi/issues/new) **only** if you want to report a bug or a feature. Don't open issues for questions or support, instead join our [Slack workspace](https://www.asyncapi.com/slack-invite) and ask there. Don't forget to follow our [Slack Etiquette](https://www.asyncapi.com/docs/community/060-meetings-and-communication/slack-etiquette) while interacting with community members! It's more likely you'll get help, and much faster!
50 |
51 | ## Bug Reports and Feature Requests
52 |
53 | Please use our issues templates that provide you with hints on what information we need from you to help you out.
54 |
55 | ## Pull Requests
56 |
57 | **Please, make sure you open an issue before starting with a Pull Request, unless it's a typo or a really obvious error.** Pull requests are the best way to propose changes to the specification. Get familiar with our document that explains [Git workflow](https://www.asyncapi.com/docs/community/010-contribution-guidelines/git-workflow) used in our repositories.
58 |
59 | ## Conventional commits
60 |
61 | Our repositories follow [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/#summary) specification. Releasing to GitHub and NPM is done with the support of [semantic-release](https://semantic-release.gitbook.io/semantic-release/).
62 |
63 | Pull requests should have a title that follows the specification, otherwise, merging is blocked. If you are not familiar with the specification simply ask maintainers to modify. You can also use this cheatsheet if you want:
64 |
65 | - `fix: ` prefix in the title indicates that PR is a bug fix and PATCH release must be triggered.
66 | - `feat: ` prefix in the title indicates that PR is a feature and MINOR release must be triggered.
67 | - `docs: ` prefix in the title indicates that PR is only related to the documentation and there is no need to trigger release.
68 | - `chore: ` prefix in the title indicates that PR is only related to cleanup in the project and there is no need to trigger release.
69 | - `test: ` prefix in the title indicates that PR is only related to tests and there is no need to trigger release.
70 | - `refactor: ` prefix in the title indicates that PR is only related to refactoring and there is no need to trigger release.
71 |
72 | What about MAJOR release? just add `!` to the prefix, like `fix!: ` or `refactor!: `
73 |
74 | Prefix that follows specification is not enough though. Remember that the title must be clear and descriptive with usage of [imperative mood](https://chris.beams.io/posts/git-commit/#imperative).
75 |
76 | Happy contributing :heart:
77 |
78 | ## License
79 | When you submit changes, your submissions are understood to be under the same [Apache 2.0 License](https://github.com/asyncapi/asyncapi/blob/master/LICENSE) that covers the project. Feel free to [contact the maintainers](https://www.asyncapi.com/slack-invite) if that's a concern.
80 |
81 | ## References
82 | This document was adapted from the open-source contribution guidelines for [Facebook's Draft](https://github.com/facebook/draft-js/blob/master/CONTRIBUTING.md).
83 |
--------------------------------------------------------------------------------
/.github/workflows/update-pr.yml:
--------------------------------------------------------------------------------
1 | # This workflow is centrally managed in https://github.com/asyncapi/.github/
2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo
3 |
4 | # This workflow will run on every comment with /update or /u. And will create merge-commits for the PR.
5 | # This also works with forks, not only with branches in the same repository/organization.
6 | # Currently, does not work with forks in different organizations.
7 |
8 | # This workflow will be distributed to all repositories in the AsyncAPI organization
9 |
10 | name: Update PR branches from fork
11 |
12 | on:
13 | issue_comment:
14 | types: [created]
15 |
16 | jobs:
17 | update-pr:
18 | if: >
19 | startsWith(github.repository, 'asyncapi/') &&
20 | github.event.issue.pull_request &&
21 | github.event.issue.state != 'closed' && (
22 | contains(github.event.comment.body, '/update') ||
23 | contains(github.event.comment.body, '/u')
24 | )
25 | runs-on: ubuntu-latest
26 | steps:
27 | - name: Get Pull Request Details
28 | id: pr
29 | uses: actions/github-script@v7
30 | with:
31 | github-token: ${{ secrets.GH_TOKEN || secrets.GITHUB_TOKEN }}
32 | previews: 'merge-info-preview' # https://docs.github.com/en/graphql/overview/schema-previews#merge-info-preview-more-detailed-information-about-a-pull-requests-merge-state-preview
33 | script: |
34 | const prNumber = context.payload.issue.number;
35 | core.debug(`PR Number: ${prNumber}`);
36 | const { data: pr } = await github.rest.pulls.get({
37 | owner: context.repo.owner,
38 | repo: context.repo.repo,
39 | pull_number: prNumber
40 | });
41 |
42 | // If the PR has conflicts, we don't want to update it
43 | const updateable = ['behind', 'blocked', 'unknown', 'draft', 'clean'].includes(pr.mergeable_state);
44 | console.log(`PR #${prNumber} is ${pr.mergeable_state} and is ${updateable ? 'updateable' : 'not updateable'}`);
45 | core.setOutput('updateable', updateable);
46 |
47 | core.debug(`Updating PR #${prNumber} with head ${pr.head.sha}`);
48 |
49 | return {
50 | id: pr.node_id,
51 | number: prNumber,
52 | head: pr.head.sha,
53 | }
54 | - name: Update the Pull Request
55 | if: steps.pr.outputs.updateable == 'true'
56 | uses: actions/github-script@v7
57 | with:
58 | github-token: ${{ secrets.GH_TOKEN || secrets.GITHUB_TOKEN }}
59 | script: |
60 | const mutation = `mutation update($input: UpdatePullRequestBranchInput!) {
61 | updatePullRequestBranch(input: $input) {
62 | pullRequest {
63 | mergeable
64 | }
65 | }
66 | }`;
67 |
68 | const pr_details = ${{ steps.pr.outputs.result }};
69 |
70 | try {
71 | const { data } = await github.graphql(mutation, {
72 | input: {
73 | pullRequestId: pr_details.id,
74 | expectedHeadOid: pr_details.head,
75 | }
76 | });
77 | } catch (GraphQLError) {
78 | core.debug(GraphQLError);
79 | if (
80 | GraphQLError.name === 'GraphqlResponseError' &&
81 | GraphQLError.errors.some(
82 | error => error.type === 'FORBIDDEN' || error.type === 'UNAUTHORIZED'
83 | )
84 | ) {
85 | // Add comment to PR if the bot doesn't have permissions to update the PR
86 | const comment = `Hi @${context.actor}. Update of PR has failed. It can be due to one of the following reasons:
87 | - I don't have permissions to update this PR. To update your fork with upstream using bot you need to enable [Allow edits from maintainers](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/allowing-changes-to-a-pull-request-branch-created-from-a-fork) option in the PR.
88 | - The fork is located in an organization, not under your personal profile. No solution for that. You are on your own with manual update.
89 | - There may be a conflict in the PR. Please resolve the conflict and try again.`;
90 |
91 | await github.rest.issues.createComment({
92 | owner: context.repo.owner,
93 | repo: context.repo.repo,
94 | issue_number: context.issue.number,
95 | body: comment
96 | });
97 |
98 | core.setFailed('Bot does not have permissions to update the PR');
99 | } else {
100 | core.setFailed(GraphQLError.message);
101 | }
102 | }
103 |
--------------------------------------------------------------------------------
/.github/workflows/bounty-program-commands.yml:
--------------------------------------------------------------------------------
1 | # This workflow is centrally managed at https://github.com/asyncapi/.github/
2 | # Don't make changes to this file in this repository, as they will be overwritten with
3 | # changes made to the same file in the abovementioned repository.
4 |
5 | # The purpose of this workflow is to allow Bounty Team members
6 | # (https://github.com/orgs/asyncapi/teams/bounty_team) to issue commands to the
7 | # organization's global AsyncAPI bot related to the Bounty Program, while at the
8 | # same time preventing unauthorized users from misusing them.
9 |
10 | name: Bounty Program commands
11 |
12 | on:
13 | issue_comment:
14 | types:
15 | - created
16 |
17 | env:
18 | BOUNTY_PROGRAM_LABELS_JSON: |
19 | [
20 | {"name": "bounty", "color": "0e8a16", "description": "Participation in the Bounty Program"}
21 | ]
22 |
23 | jobs:
24 | guard-against-unauthorized-use:
25 | if: >
26 | github.actor != ('aeworxet' || 'thulieblack') &&
27 | (
28 | startsWith(github.event.comment.body, '/bounty' )
29 | )
30 |
31 | runs-on: ubuntu-latest
32 |
33 | steps:
34 | - name: ❌ @${{github.actor}} made an unauthorized attempt to use a Bounty Program's command
35 | uses: actions/github-script@v7
36 | env:
37 | ACTOR: ${{ github.actor }}
38 | with:
39 | github-token: ${{ secrets.GH_TOKEN }}
40 | script: |
41 | const commentText = `❌ @${process.env.ACTOR} is not authorized to use the Bounty Program's commands.
42 | These commands can only be used by members of the [Bounty Team](https://github.com/orgs/asyncapi/teams/bounty_team).`;
43 |
44 | console.log(`❌ @${process.env.ACTOR} made an unauthorized attempt to use a Bounty Program's command.`);
45 | github.rest.issues.createComment({
46 | issue_number: context.issue.number,
47 | owner: context.repo.owner,
48 | repo: context.repo.repo,
49 | body: commentText
50 | })
51 |
52 | add-label-bounty:
53 | if: >
54 | github.actor == ('aeworxet' || 'thulieblack') &&
55 | (
56 | startsWith(github.event.comment.body, '/bounty' )
57 | )
58 |
59 | runs-on: ubuntu-latest
60 |
61 | steps:
62 | - name: Add label `bounty`
63 | uses: actions/github-script@v7
64 | with:
65 | github-token: ${{ secrets.GH_TOKEN }}
66 | script: |
67 | const BOUNTY_PROGRAM_LABELS = JSON.parse(process.env.BOUNTY_PROGRAM_LABELS_JSON);
68 | let LIST_OF_LABELS_FOR_REPO = await github.rest.issues.listLabelsForRepo({
69 | owner: context.repo.owner,
70 | repo: context.repo.repo,
71 | });
72 |
73 | LIST_OF_LABELS_FOR_REPO = LIST_OF_LABELS_FOR_REPO.data.map(key => key.name);
74 |
75 | if (!LIST_OF_LABELS_FOR_REPO.includes(BOUNTY_PROGRAM_LABELS[0].name)) {
76 | await github.rest.issues.createLabel({
77 | owner: context.repo.owner,
78 | repo: context.repo.repo,
79 | name: BOUNTY_PROGRAM_LABELS[0].name,
80 | color: BOUNTY_PROGRAM_LABELS[0].color,
81 | description: BOUNTY_PROGRAM_LABELS[0].description
82 | });
83 | }
84 |
85 | console.log('Adding label `bounty`...');
86 | github.rest.issues.addLabels({
87 | issue_number: context.issue.number,
88 | owner: context.repo.owner,
89 | repo: context.repo.repo,
90 | labels: [BOUNTY_PROGRAM_LABELS[0].name]
91 | })
92 |
93 | remove-label-bounty:
94 | if: >
95 | github.actor == ('aeworxet' || 'thulieblack') &&
96 | (
97 | startsWith(github.event.comment.body, '/unbounty' )
98 | )
99 |
100 | runs-on: ubuntu-latest
101 |
102 | steps:
103 | - name: Remove label `bounty`
104 | uses: actions/github-script@v7
105 | with:
106 | github-token: ${{ secrets.GH_TOKEN }}
107 | script: |
108 | const BOUNTY_PROGRAM_LABELS = JSON.parse(process.env.BOUNTY_PROGRAM_LABELS_JSON);
109 | let LIST_OF_LABELS_FOR_ISSUE = await github.rest.issues.listLabelsOnIssue({
110 | owner: context.repo.owner,
111 | repo: context.repo.repo,
112 | issue_number: context.issue.number,
113 | });
114 |
115 | LIST_OF_LABELS_FOR_ISSUE = LIST_OF_LABELS_FOR_ISSUE.data.map(key => key.name);
116 |
117 | if (LIST_OF_LABELS_FOR_ISSUE.includes(BOUNTY_PROGRAM_LABELS[0].name)) {
118 | console.log('Removing label `bounty`...');
119 | github.rest.issues.removeLabel({
120 | issue_number: context.issue.number,
121 | owner: context.repo.owner,
122 | repo: context.repo.repo,
123 | name: [BOUNTY_PROGRAM_LABELS[0].name]
124 | })
125 | }
126 |
--------------------------------------------------------------------------------
/.github/workflows/if-nodejs-release.yml:
--------------------------------------------------------------------------------
1 | # This action is centrally managed in https://github.com/asyncapi/.github/
2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo
3 |
4 | # It does magic only if there is package.json file in the root of the project
5 | name: Release - if Node project
6 |
7 | on:
8 | push:
9 | branches:
10 | - master
11 | # below lines are not enough to have release supported for these branches
12 | # make sure configuration of `semantic-release` package mentions these branches
13 | - next-spec
14 | - next-major
15 | - next-major-spec
16 | - beta
17 | - alpha
18 |
19 | jobs:
20 |
21 | test-nodejs:
22 | # We just check the message of first commit as there is always just one commit because we squash into one before merging
23 | # "commits" contains array of objects where one of the properties is commit "message"
24 | # Release workflow will be skipped if release conventional commits are not used
25 | if: |
26 | startsWith( github.repository, 'asyncapi/' ) &&
27 | (startsWith( github.event.commits[0].message , 'fix:' ) ||
28 | startsWith( github.event.commits[0].message, 'fix!:' ) ||
29 | startsWith( github.event.commits[0].message, 'feat:' ) ||
30 | startsWith( github.event.commits[0].message, 'feat!:' ))
31 | name: Test NodeJS release on ${{ matrix.os }}
32 | runs-on: ${{ matrix.os }}
33 | strategy:
34 | matrix:
35 | os: [ubuntu-latest, macos-latest, windows-latest]
36 | steps:
37 | - name: Set git to use LF #to once and for all finish neverending fight between Unix and Windows
38 | run: |
39 | git config --global core.autocrlf false
40 | git config --global core.eol lf
41 | - name: Checkout repository
42 | uses: actions/checkout@v2
43 | - name: Check if Node.js project and has package.json
44 | id: packagejson
45 | run: test -e ./package.json && echo "::set-output name=exists::true" || echo "::set-output name=exists::false"
46 | shell: bash
47 | - if: steps.packagejson.outputs.exists == 'true'
48 | name: Setup Node.js
49 | uses: actions/setup-node@v2
50 | with:
51 | node-version: 14
52 | cache: 'npm'
53 | cache-dependency-path: '**/package-lock.json'
54 | - if: steps.packagejson.outputs.exists == 'true'
55 | name: Install dependencies
56 | run: npm install
57 | - if: steps.packagejson.outputs.exists == 'true'
58 | name: Run test
59 | run: npm test
60 | - if: failure() # Only, on failure, send a message on the 94_bot-failing-ci slack channel
61 | name: Report workflow run status to Slack
62 | uses: 8398a7/action-slack@v3
63 | with:
64 | status: ${{ job.status }}
65 | fields: repo,action,workflow
66 | text: 'Release workflow failed in testing job'
67 | env:
68 | SLACK_WEBHOOK_URL: ${{ secrets.SLACK_CI_FAIL_NOTIFY }}
69 |
70 | release:
71 | needs: [test-nodejs]
72 | name: Publish to any of NPM, Github, and Docker Hub
73 | runs-on: ubuntu-latest
74 | steps:
75 | - name: Set git to use LF #to once and for all finish neverending fight between Unix and Windows
76 | run: |
77 | git config --global core.autocrlf false
78 | git config --global core.eol lf
79 | - name: Checkout repository
80 | uses: actions/checkout@v2
81 | - name: Check if Node.js project and has package.json
82 | id: packagejson
83 | run: test -e ./package.json && echo "::set-output name=exists::true" || echo "::set-output name=exists::false"
84 | - if: steps.packagejson.outputs.exists == 'true'
85 | name: Setup Node.js
86 | uses: actions/setup-node@v1
87 | with:
88 | node-version: 14
89 | - if: steps.packagejson.outputs.exists == 'true'
90 | name: Install dependencies
91 | run: npm install
92 | - if: steps.packagejson.outputs.exists == 'true'
93 | name: Publish to any of NPM, Github, and Docker Hub
94 | id: release
95 | env:
96 | GITHUB_TOKEN: ${{ secrets.GH_TOKEN }}
97 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
98 | DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
99 | DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}
100 | GIT_AUTHOR_NAME: asyncapi-bot
101 | GIT_AUTHOR_EMAIL: info@asyncapi.io
102 | GIT_COMMITTER_NAME: asyncapi-bot
103 | GIT_COMMITTER_EMAIL: info@asyncapi.io
104 | run: npm run release
105 | - if: failure() # Only, on failure, send a message on the 94_bot-failing-ci slack channel
106 | name: Report workflow run status to Slack
107 | uses: 8398a7/action-slack@v3
108 | with:
109 | status: ${{ job.status }}
110 | fields: repo,action,workflow
111 | text: 'Release workflow failed in release job'
112 | env:
113 | SLACK_WEBHOOK_URL: ${{ secrets.SLACK_CI_FAIL_NOTIFY }}
--------------------------------------------------------------------------------
/.github/workflows/release-announcements.yml:
--------------------------------------------------------------------------------
1 | # This action is centrally managed in https://github.com/asyncapi/.github/
2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo
3 |
4 | name: 'Announce releases in different channels'
5 |
6 | on:
7 | release:
8 | types:
9 | - published
10 |
11 | jobs:
12 |
13 | slack-announce:
14 | name: Slack - notify on every release
15 | runs-on: ubuntu-latest
16 | steps:
17 | - name: Checkout repository
18 | uses: actions/checkout@v4
19 | - name: Convert markdown to slack markdown for issue
20 | # This workflow is from our own org repo and safe to reference by 'master'.
21 | uses: asyncapi/.github/.github/actions/slackify-markdown@master # //NOSONAR
22 | id: markdown
23 | env:
24 | RELEASE_TAG: ${{github.event.release.tag_name}}
25 | RELEASE_URL: ${{github.event.release.html_url}}
26 | RELEASE_BODY: ${{ github.event.release.body }}
27 | with:
28 | markdown: "[${{ env.RELEASE_TAG }}](${{ env.RELEASE_URL }}) \n ${{ env.RELEASE_BODY }}"
29 | - name: Send info about release to Slack
30 | uses: rtCamp/action-slack-notify@c33737706dea87cd7784c687dadc9adf1be59990 # Using v2.3.2
31 | env:
32 | SLACK_WEBHOOK: ${{ secrets.SLACK_RELEASES }}
33 | SLACK_TITLE: Release ${{ env.RELEASE_TAG }} for ${{ env.REPO_NAME }} is out in the wild 😱💪🍾🎂
34 | SLACK_MESSAGE: ${{steps.markdown.outputs.text}}
35 | MSG_MINIMAL: true
36 | RELEASE_TAG: ${{github.event.release.tag_name}}
37 | REPO_NAME: ${{github.repository}}
38 |
39 | twitter-announce:
40 | name: Twitter - notify on minor and major releases
41 | runs-on: ubuntu-latest
42 | steps:
43 | - name: Checkout repo
44 | uses: actions/checkout@v4
45 | - name: Get version of last and previous release
46 | uses: actions/github-script@v7
47 | id: versions
48 | with:
49 | github-token: ${{ secrets.GITHUB_TOKEN }}
50 | script: |
51 | const query = `query($owner:String!, $name:String!) {
52 | repository(owner:$owner, name:$name){
53 | releases(first: 2, orderBy: {field: CREATED_AT, direction: DESC}) {
54 | nodes {
55 | name
56 | }
57 | }
58 | }
59 | }`;
60 | const variables = {
61 | owner: context.repo.owner,
62 | name: context.repo.repo
63 | };
64 | const { repository: { releases: { nodes } } } = await github.graphql(query, variables);
65 | core.setOutput('lastver', nodes[0].name);
66 | // In case of first release in the package, there is no such thing as previous error, so we set info about previous version only once we have it
67 | // We should tweet about the release no matter of the type as it is initial release
68 | if (nodes.length != 1) core.setOutput('previousver', nodes[1].name);
69 | - name: Identify release type
70 | id: releasetype
71 | # if previousver is not provided then this steps just logs information about missing version, no errors
72 | env:
73 | PREV_VERSION: ${{steps.versions.outputs.previousver}}
74 | LAST_VERSION: ${{steps.versions.outputs.lastver}}
75 | run: echo "type=$(npx -q -p semver-diff-cli semver-diff "$PREV_VERSION" "$LAST_VERSION")" >> $GITHUB_OUTPUT
76 | - name: Get name of the person that is behind the newly released version
77 | id: author
78 | run: |
79 | AUTHOR_NAME=$(git log -1 --pretty=format:'%an')
80 | printf 'name=%s\n' "$AUTHOR_NAME" >> $GITHUB_OUTPUT
81 | - name: Publish information about the release to Twitter # tweet only if detected version change is not a patch
82 | # tweet goes out even if the type is not major or minor but "You need provide version number to compare."
83 | # it is ok, it just means we did not identify previous version as we are tweeting out information about the release for the first time
84 | if: steps.releasetype.outputs.type != 'null' && steps.releasetype.outputs.type != 'patch' # null means that versions are the same
85 | uses: m1ner79/Github-Twittction@d1e508b6c2170145127138f93c49b7c46c6ff3a7 # using 2.0.0 https://github.com/m1ner79/Github-Twittction/releases/tag/v2.0.0
86 | env:
87 | RELEASE_TAG: ${{github.event.release.tag_name}}
88 | REPO_NAME: ${{github.repository}}
89 | AUTHOR_NAME: ${{ steps.author.outputs.name }}
90 | RELEASE_URL: ${{github.event.release.html_url}}
91 | with:
92 | twitter_status: "Release ${{ env.RELEASE_TAG }} for ${{ env.REPO_NAME }} is out in the wild 😱💪🍾🎂\n\nThank you for the contribution ${{ env.AUTHOR_NAME }} ${{ env.RELEASE_URL }}"
93 | twitter_consumer_key: ${{ secrets.TWITTER_CONSUMER_KEY }}
94 | twitter_consumer_secret: ${{ secrets.TWITTER_CONSUMER_SECRET }}
95 | twitter_access_token_key: ${{ secrets.TWITTER_ACCESS_TOKEN_KEY }}
96 | twitter_access_token_secret: ${{ secrets.TWITTER_ACCESS_TOKEN_SECRET }}
--------------------------------------------------------------------------------
/.github/workflows/automerge-for-humans-add-ready-to-merge-or-do-not-merge-label.yml:
--------------------------------------------------------------------------------
1 | # This workflow is centrally managed in https://github.com/asyncapi/.github/
2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo
3 |
4 | # Purpose of this workflow is to enable anyone to label PR with the following labels:
5 | # `ready-to-merge` and `do-not-merge` labels to get stuff merged or blocked from merging
6 | # `autoupdate` to keep a branch up-to-date with the target branch
7 |
8 | name: Label PRs # if proper comment added
9 |
10 | on:
11 | issue_comment:
12 | types:
13 | - created
14 |
15 | jobs:
16 | add-ready-to-merge-label:
17 | if: >
18 | github.event.issue.pull_request &&
19 | github.event.issue.state != 'closed' &&
20 | github.actor != 'asyncapi-bot' &&
21 | (
22 | contains(github.event.comment.body, '/ready-to-merge') ||
23 | contains(github.event.comment.body, '/rtm' )
24 | )
25 |
26 | runs-on: ubuntu-latest
27 | steps:
28 | - name: Add ready-to-merge label
29 | uses: actions/github-script@v7
30 | env:
31 | GITHUB_ACTOR: ${{ github.actor }}
32 | with:
33 | github-token: ${{ secrets.GH_TOKEN }}
34 | script: |
35 | const prDetailsUrl = context.payload.issue.pull_request.url;
36 | const { data: pull } = await github.request(prDetailsUrl);
37 | const { draft: isDraft} = pull;
38 | if(!isDraft) {
39 | console.log('adding ready-to-merge label...');
40 | github.rest.issues.addLabels({
41 | issue_number: context.issue.number,
42 | owner: context.repo.owner,
43 | repo: context.repo.repo,
44 | labels: ['ready-to-merge']
45 | })
46 | }
47 |
48 | const { data: comparison } =
49 | await github.rest.repos.compareCommitsWithBasehead({
50 | owner: pull.head.repo.owner.login,
51 | repo: pull.head.repo.name,
52 | basehead: `${pull.base.label}...${pull.head.label}`,
53 | });
54 | if (comparison.behind_by !== 0 && pull.mergeable_state === 'behind') {
55 | console.log(`This branch is behind the target by ${comparison.behind_by} commits`)
56 | console.log('adding out-of-date comment...');
57 | github.rest.issues.createComment({
58 | issue_number: context.issue.number,
59 | owner: context.repo.owner,
60 | repo: context.repo.repo,
61 | body: `Hello, @${process.env.GITHUB_ACTOR}! 👋🏼
62 | This PR is not up to date with the base branch and can't be merged.
63 | Please update your branch manually with the latest version of the base branch.
64 | PRO-TIP: To request an update from the upstream branch, simply comment \`/u\` or \`/update\` and our bot will handle the update operation promptly.
65 |
66 | The only requirement for this to work is to enable [Allow edits from maintainers](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/allowing-changes-to-a-pull-request-branch-created-from-a-fork) option in your PR. Also the update will not work if your fork is located in an organization, not under your personal profile.
67 | Thanks 😄`
68 | })
69 | }
70 |
71 | add-do-not-merge-label:
72 | if: >
73 | github.event.issue.pull_request &&
74 | github.event.issue.state != 'closed' &&
75 | github.actor != 'asyncapi-bot' &&
76 | (
77 | contains(github.event.comment.body, '/do-not-merge') ||
78 | contains(github.event.comment.body, '/dnm' )
79 | )
80 | runs-on: ubuntu-latest
81 | steps:
82 | - name: Add do-not-merge label
83 | uses: actions/github-script@v7
84 | with:
85 | github-token: ${{ secrets.GH_TOKEN }}
86 | script: |
87 | github.rest.issues.addLabels({
88 | issue_number: context.issue.number,
89 | owner: context.repo.owner,
90 | repo: context.repo.repo,
91 | labels: ['do-not-merge']
92 | })
93 | add-autoupdate-label:
94 | if: >
95 | github.event.issue.pull_request &&
96 | github.event.issue.state != 'closed' &&
97 | github.actor != 'asyncapi-bot' &&
98 | (
99 | contains(github.event.comment.body, '/autoupdate') ||
100 | contains(github.event.comment.body, '/au' )
101 | )
102 | runs-on: ubuntu-latest
103 | steps:
104 | - name: Add autoupdate label
105 | uses: actions/github-script@v7
106 | with:
107 | github-token: ${{ secrets.GH_TOKEN }}
108 | script: |
109 | github.rest.issues.addLabels({
110 | issue_number: context.issue.number,
111 | owner: context.repo.owner,
112 | repo: context.repo.repo,
113 | labels: ['autoupdate']
114 | })
115 |
--------------------------------------------------------------------------------
/test/common.test.spec.js:
--------------------------------------------------------------------------------
1 | import AsyncAPIDocument from '@asyncapi/parser/lib/models/asyncapi';
2 | import { getChannels } from '../utils/common';
3 |
4 | const contentType = 'application/json';
5 |
6 | describe('Common utilities', () => {
7 | it('should handle multiple operations in one channel', () => {
8 | const asyncapi = new AsyncAPIDocument({
9 | asyncapi: '2.2.0',
10 | defaultContentType: contentType,
11 | channels: {
12 | '{sensorId}.temperature': {
13 | parameters: {
14 | sensorId: {
15 | 'x-example': 'SENSOR-001',
16 | description: 'Id of the temperature sensor.',
17 | schema: { type: 'string' },
18 | },
19 | },
20 | bindings: {
21 | amqp: {
22 | is: 'routingKey',
23 | exchange: { name: 'temperature', type: 'topic', vhost: '/iot' },
24 | queue: { name: 'temperatures' },
25 | },
26 | },
27 | publish: {
28 | operationId: 'onSpecificSensorTemperatureReceived',
29 | description: 'Publish a temperature change.',
30 | bindings: {
31 | amqp: {
32 | expiration: 100000,
33 | userId: 'guest',
34 | cc: ['lkab.user.logs'],
35 | bcc: ['lkab.audit'],
36 | priority: 10,
37 | deliveryMode: 2,
38 | mandatory: false,
39 | replyTo: 'user.signedup',
40 | timestamp: true,
41 | ack: true,
42 | },
43 | },
44 | message: {
45 | payload: {
46 | id: 'temperature',
47 | type: 'object',
48 | additionalProperties: false,
49 | properties: {
50 | celsius: { type: 'number', format: 'decimal' },
51 | kelvin: { type: 'number', format: 'decimal' },
52 | fahrenheit: { type: 'number', format: 'decimal' },
53 | origin: { type: ['null', 'string'] },
54 | created: { type: 'string', format: 'date-time' },
55 | },
56 | },
57 | name: 'temperature',
58 | },
59 | },
60 | subscribe: {
61 | operationId: 'onSensorTemperatureChange',
62 | description:
63 | 'Subscribe to a temperature change from a specific sensor.',
64 | message: {
65 | payload: {
66 | id: 'temperature',
67 | type: 'object',
68 | additionalProperties: false,
69 | properties: {
70 | celsius: { type: 'number', format: 'decimal' },
71 | kelvin: { type: 'number', format: 'decimal' },
72 | fahrenheit: { type: 'number', format: 'decimal' },
73 | origin: { type: ['null', 'string'] },
74 | created: { type: 'string', format: 'date-time' },
75 | },
76 | },
77 | name: 'temperature',
78 | },
79 | },
80 | },
81 | },
82 | });
83 |
84 | const channels = getChannels(asyncapi);
85 | expect(channels).toBeDefined();
86 | expect(channels.length).toBe(1);
87 |
88 | const subscriber = channels[0].subscriber;
89 | expect(subscriber).toBeDefined();
90 | expect(subscriber.operationId).toBe('OnSensorTemperatureChange');
91 |
92 | const publisher = channels[0].publisher;
93 | expect(publisher).toBeDefined();
94 | expect(publisher.operationId).toBe('OnSpecificSensorTemperatureReceived');
95 | });
96 |
97 | it('should create flat object from channels', () => {
98 | const asyncapi = new AsyncAPIDocument({
99 | asyncapi: '2.2.0',
100 | defaultContentType: contentType,
101 | channels: {
102 | '{sensorId}.temperature': {
103 | subscribe: {
104 | operationId: 'onSpecificSensorTemperatureReceived',
105 | description:
106 | 'Subscribe to a temperature change from a specific sensor.',
107 | message: {
108 | payload: {
109 | id: 'temperature',
110 | type: 'object',
111 | additionalProperties: false,
112 | properties: {
113 | celsius: { type: 'number', format: 'decimal' },
114 | kelvin: { type: 'number', format: 'decimal' },
115 | fahrenheit: { type: 'number', format: 'decimal' },
116 | origin: { type: ['null', 'string'] },
117 | created: { type: 'string', format: 'date-time' },
118 | },
119 | },
120 | name: 'temperature',
121 | },
122 | },
123 | parameters: {
124 | sensorId: {
125 | 'x-example': 'SENSOR-001',
126 | description: 'Id of the temperature sensor.',
127 | schema: { type: 'string' },
128 | },
129 | },
130 | bindings: {
131 | amqp: {
132 | is: 'routingKey',
133 | exchange: { name: 'temperature', type: 'topic', vhost: '/abc' },
134 | queue: { name: 'temperatures' },
135 | },
136 | },
137 | },
138 | },
139 | });
140 |
141 | const channels = getChannels(asyncapi);
142 | expect(channels).toBeDefined();
143 | expect(channels.length).toBe(1);
144 |
145 | const channel = channels[0];
146 | expect(channel.subscriber.operationId).toBe(
147 | 'OnSpecificSensorTemperatureReceived'
148 | );
149 | expect(channel.exchange).toBe('temperature');
150 | expect(channel.exchangeType).toBe('topic');
151 | expect(channel.vhost).toBe('/abc');
152 | expect(channel.queue).toBe('temperatures');
153 | });
154 |
155 | it('should handle empty channels', () => {
156 | const asyncapi = new AsyncAPIDocument({
157 | asyncapi: '2.2.0',
158 | defaultContentType: contentType,
159 | });
160 |
161 | const channels = getChannels(asyncapi);
162 | expect(channels.length).toBe(0);
163 | });
164 | });
165 |
--------------------------------------------------------------------------------
/components/templates/amqpservice.js:
--------------------------------------------------------------------------------
1 | import { getChannels } from '../../utils/common';
2 |
3 | const template = (asyncapi, params) => {
4 | const channels = getChannels(asyncapi);
5 |
6 | if (channels.length === 0) {
7 | return null;
8 | }
9 |
10 | return `using System;
11 | using System.Collections.Generic;
12 | using System.Text;
13 | using System.Text.Json;
14 | using Microsoft.Extensions.Configuration;
15 | using ${params.namespace}.Models;
16 | using ${params.namespace}.Services.Interfaces;
17 | using RabbitMQ.Client;
18 | using RabbitMQ.Client.Events;
19 | using Serilog;
20 |
21 | namespace ${params.namespace}.Services;
22 |
23 | ///
24 | /// Generated consumer for ${asyncapi.info().title()}, ${asyncapi
25 | .info()
26 | .version()}
27 | ///
28 | public class AmqpService : IAmqpService
29 | {
30 | private readonly IConfiguration _configuration;
31 | private readonly ILogger _logger = Log.ForContext();
32 | private readonly IChannelPool _channelPool;
33 | private readonly IConnection _connection;
34 |
35 | public AmqpService(IConfiguration configuration)
36 | {
37 | _configuration = configuration;
38 |
39 | var user = _configuration["RabbitMq:User"];
40 | var password = _configuration["RabbitMq:Password"];
41 | var host = _configuration["RabbitMq:Host"];
42 |
43 | var factory = new ConnectionFactory
44 | {
45 | Uri = new Uri($"amqps://{user}:{password}@{host}"),
46 | RequestedHeartbeat = TimeSpan.FromSeconds(10)
47 | };
48 |
49 | _connection = factory.CreateConnection();
50 | _channelPool = ChannelPool.Create(_connection);
51 | }
52 |
53 | ${channels
54 | .filter((channel) => channel.publisher)
55 | .map(
56 | (channel) => `///
57 | /// Operations from async api specification
58 | ///
59 | /// The message to be handled by this amqp operation
60 | public void ${channel.publisher.operationId}(${channel.publisher.messageType} message)
61 | {
62 | var exchange = "${channel.exchange}";
63 | var routingKey = "${channel.routingKey}";
64 |
65 | var channel = _channelPool.GetChannel("${channel.publisher.operationId}");
66 | var exchangeProps = new Dictionary
67 | {
68 | {"CC", "${channel.publisher.cc}"},
69 | {"BCC", "${channel.publisher.bcc}"},
70 | {"alternate-exchange", "${channel.publisher.alternateExchange}"},
71 | };
72 |
73 | channel.ExchangeDeclare(
74 | exchange: exchange, // exchange.name from channel binding
75 | type: "${channel.publisher.exchangeType}", // type from channel binding
76 | ${channel.isDurable}, // durable from channel binding
77 | ${channel.isAutoDelete}, // autoDelete from channel binding
78 | exchangeProps);
79 |
80 | var props = channel.CreateBasicProperties();
81 |
82 | props.CorrelationId = $"{Guid.NewGuid()}";
83 | props.ReplyTo = "${channel.publisher.replyTo}";
84 | props.DeliveryMode = Byte.Parse("${channel.publisher.deliveryMode}");
85 | props.Priority = ${channel.publisher.priority};
86 | props.Timestamp = new AmqpTimestamp(DateTimeOffset.UnixEpoch.Ticks);
87 | props.Expiration = "${channel.publisher.expiration}";
88 |
89 | _logger.Verbose("Sending message {@${channel.publisher.messageType}} with correlation id {CorrelationId}",
90 | message,
91 | props.CorrelationId);
92 |
93 | var body = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(message));
94 |
95 | channel.BasicPublish(exchange: exchange,
96 | routingKey: routingKey,
97 | mandatory: ${channel.publisher.mandatory},
98 | basicProperties: props,
99 | body: body);
100 | }
101 |
102 | `
103 | )
104 | .join('')}
105 |
106 | ${channels
107 | .filter((channel) => channel.subscriber)
108 | .map(
109 | (channel) => `public void ${channel.subscriber.operationId}()
110 | {
111 | var queue = "${channel.queue}"; // queue from specification
112 | var channel = _channelPool.GetChannel("${channel.subscriber.operationId}");
113 |
114 | // TODO: declare passive?
115 | channel.QueueDeclare(queue);
116 |
117 | // IMPORTANT! If the routing key contains {some-parameter-name}
118 | // you must change the routing key below to something meaningful for amqp service listening for messages.
119 | // For demo purposes you can just replace it with the wildcard '#' which means it recieves
120 | // all messages no matter what the parameter is.
121 | channel.QueueBind(queue: queue,
122 | exchange: "${channel.exchange}",
123 | routingKey: "${channel.routingKey}");
124 |
125 | var consumer = new EventingBasicConsumer(channel);
126 | consumer.Received += (_, ea) =>
127 | {
128 | var body = ea.Body.ToArray();
129 | var message = JsonSerializer.Deserialize<${channel.subscriber.messageType}>(Encoding.UTF8.GetString(body));
130 | _logger.Verbose("${channel.subscriber.messageType} received, {@${channel.subscriber.messageType}}", message);
131 |
132 | try
133 | {
134 | // Handle message
135 |
136 | channel.BasicAck(ea.DeliveryTag, true);
137 | }
138 | catch (Exception e)
139 | {
140 | _logger.Error(e, "Something went wrong trying to process message {@${channel.subscriber.messageType}},", message);
141 | channel.BasicReject(ea.DeliveryTag, false);
142 | }
143 | };
144 |
145 | channel.BasicConsume(queue: queue,
146 | autoAck: false,
147 | consumer: consumer);
148 | }
149 | `
150 | )
151 | .join('')}
152 |
153 | public void Dispose()
154 | {
155 | _channelPool?.Dispose();
156 | _connection?.Dispose();
157 | }
158 | }`;
159 | };
160 |
161 | export function AmqpService({ asyncapi, params }) {
162 | if (!asyncapi.hasChannels()) {
163 | return null;
164 | }
165 |
166 | return template(asyncapi, params);
167 | }
168 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 |
2 | # Contributor Covenant 3.0 Code of Conduct
3 |
4 | ## Our Pledge
5 |
6 | We pledge to make our community welcoming, safe, and equitable for all.
7 |
8 | We are committed to fostering an environment that respects and promotes the dignity, rights, and contributions of all individuals, regardless of characteristics including race, ethnicity, caste, color, age, physical characteristics, neurodiversity, disability, sex or gender, gender identity or expression, sexual orientation, language, philosophy or religion, national or social origin, socio-economic position, level of education, or other status. The same privileges of participation are extended to everyone who participates in good faith and in accordance with this Covenant.
9 |
10 | ## Encouraged Behaviors
11 |
12 | While acknowledging differences in social norms, we all strive to meet our community's expectations for positive behavior. We also understand that our words and actions may be interpreted differently than we intend based on culture, background, or native language.
13 |
14 | With these considerations in mind, we agree to behave mindfully toward each other and act in ways that center our shared values, including:
15 |
16 | 1. Respecting the **purpose of our community**, our activities, and our ways of gathering.
17 | 2. Engaging **kindly and honestly** with others.
18 | 3. Respecting **different viewpoints** and experiences.
19 | 4. **Taking responsibility** for our actions and contributions.
20 | 5. Gracefully giving and accepting **constructive feedback**.
21 | 6. Committing to **repairing harm** when it occurs.
22 | 7. Behaving in other ways that promote and sustain the **well-being of our community**.
23 |
24 |
25 | ## Restricted Behaviors
26 |
27 | We agree to restrict the following behaviors in our community. Instances, threats, and promotion of these behaviors are violations of this Code of Conduct.
28 |
29 | 1. **Harassment.** Violating explicitly expressed boundaries or engaging in unnecessary personal attention after any clear request to stop.
30 | 2. **Character attacks.** Making insulting, demeaning, or pejorative comments directed at a community member or group of people.
31 | 3. **Stereotyping or discrimination.** Characterizing anyone’s personality or behavior on the basis of immutable identities or traits.
32 | 4. **Sexualization.** Behaving in a way that would generally be considered inappropriately intimate in the context or purpose of the community.
33 | 5. **Violating confidentiality**. Sharing or acting on someone's personal or private information without their permission.
34 | 6. **Endangerment.** Causing, encouraging, or threatening violence or other harm toward any person or group.
35 | 7. Behaving in other ways that **threaten the well-being** of our community.
36 |
37 | ### Other Restrictions
38 |
39 | 1. **Misleading identity.** Impersonating someone else for any reason, or pretending to be someone else to evade enforcement actions.
40 | 2. **Failing to credit sources.** Not properly crediting the sources of content you contribute.
41 | 3. **Promotional materials**. Sharing marketing or other commercial content in a way that is outside the norms of the community.
42 | 4. **Irresponsible communication.** Failing to responsibly present content which includes, links or describes any other restricted behaviors.
43 |
44 |
45 | ## Reporting an Issue
46 |
47 | Tensions can occur between community members even when they are trying their best to collaborate. Not every conflict represents a code of conduct violation, and this Code of Conduct reinforces encouraged behaviors and norms that can help avoid conflicts and minimize harm.
48 |
49 | When an incident does occur, it is important to report it promptly. To report a possible violation, here are a few simple ways to do it:
50 |
51 | - Join our [AsyncAPI Slack](https://asyncapi.com/slack-invite) and share your report in the `#coc` channel.
52 | - Reach out directly to any member of the [Code of Conduct Committee](https://github.com/orgs/asyncapi/teams/code_of_conduct).
53 | - Or, if you’d prefer, just send us an email at **conduct@asyncapi.com**.
54 |
55 | Community Moderators take reports of violations seriously and will make every effort to respond in a timely manner. They will investigate all reports of code of conduct violations, reviewing messages, logs, and recordings, or interviewing witnesses and other participants. Community Moderators will keep investigation and enforcement actions as transparent as possible while prioritizing safety and confidentiality. In order to honor these values, enforcement actions are carried out in private with the involved parties, but communicating to the whole community may be part of a mutually agreed upon resolution.
56 |
57 |
58 | ## Addressing and Repairing Harm
59 |
60 | ****
61 |
62 | If an investigation by the Community Moderators finds that this Code of Conduct has been violated, the following enforcement ladder may be used to determine how best to repair harm, based on the incident's impact on the individuals involved and the community as a whole. Depending on the severity of a violation, lower rungs on the ladder may be skipped.
63 |
64 | 1) Warning
65 | 1) Event: A violation involving a single incident or series of incidents.
66 | 2) Consequence: A private, written warning from the Community Moderators.
67 | 3) Repair: Examples of repair include a private written apology, acknowledgement of responsibility, and seeking clarification on expectations.
68 | 2) Temporarily Limited Activities
69 | 1) Event: A repeated incidence of a violation that previously resulted in a warning, or the first incidence of a more serious violation.
70 | 2) Consequence: A private, written warning with a time-limited cooldown period designed to underscore the seriousness of the situation and give the community members involved time to process the incident. The cooldown period may be limited to particular communication channels or interactions with particular community members.
71 | 3) Repair: Examples of repair may include making an apology, using the cooldown period to reflect on actions and impact, and being thoughtful about re-entering community spaces after the period is over.
72 | 3) Temporary Suspension
73 | 1) Event: A pattern of repeated violation which the Community Moderators have tried to address with warnings, or a single serious violation.
74 | 2) Consequence: A private written warning with conditions for return from suspension. In general, temporary suspensions give the person being suspended time to reflect upon their behavior and possible corrective actions.
75 | 3) Repair: Examples of repair include respecting the spirit of the suspension, meeting the specified conditions for return, and being thoughtful about how to reintegrate with the community when the suspension is lifted.
76 | 4) Permanent Ban
77 | 1) Event: A pattern of repeated code of conduct violations that other steps on the ladder have failed to resolve, or a violation so serious that the Community Moderators determine there is no way to keep the community safe with this person as a member.
78 | 2) Consequence: Access to all community spaces, tools, and communication channels is removed. In general, permanent bans should be rarely used, should have strong reasoning behind them, and should only be resorted to if working through other remedies has failed to change the behavior.
79 | 3) Repair: There is no possible repair in cases of this severity.
80 |
81 | This enforcement ladder is intended as a guideline. It does not limit the ability of Community Managers to use their discretion and judgment, in keeping with the best interests of our community.
82 |
83 |
84 | ## Scope
85 |
86 | This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public or other spaces. Examples of representing our community include using an official email address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
87 |
88 |
89 | ## Attribution
90 |
91 | This Code of Conduct is adapted from the Contributor Covenant, version 3.0, permanently available at [https://www.contributor-covenant.org/version/3/0/](https://www.contributor-covenant.org/version/3/0/).
92 |
93 | Contributor Covenant is stewarded by the Organization for Ethical Source and licensed under CC BY-SA 4.0. To view a copy of this license, visit [https://creativecommons.org/licenses/by-sa/4.0/](https://creativecommons.org/licenses/by-sa/4.0/)
94 |
95 | For answers to common questions about Contributor Covenant, see the FAQ at [https://www.contributor-covenant.org/faq](https://www.contributor-covenant.org/faq). Translations are provided at [https://www.contributor-covenant.org/translations](https://www.contributor-covenant.org/translations). Additional enforcement and community guideline resources can be found at [https://www.contributor-covenant.org/resources](https://www.contributor-covenant.org/resources). The enforcement ladder was inspired by the work of [Mozilla’s code of conduct team](https://github.com/mozilla/inclusion).
--------------------------------------------------------------------------------
/utils/common.js:
--------------------------------------------------------------------------------
1 | import { FormatHelpers } from '@asyncapi/modelina';
2 | // eslint-disable-next-line no-unused-vars
3 | import { Message, Schema } from '@asyncapi/parser';
4 | import _ from 'lodash';
5 | const contentTypeJSON = 'application/json';
6 | const contentTypeString = 'text/plain';
7 | const contentTypeBinary = 'application/octet-stream';
8 |
9 | /**
10 | * @typedef TemplateParameters
11 | * @type {object}
12 | * @property {boolean} generateTestClient - whether or not test client should be generated.
13 | * @property {boolean} promisifyReplyCallback - whether or not reply callbacks should be promisify.
14 | */
15 |
16 | /**
17 | * Should the callbacks be promisify.
18 | *
19 | * @param {TemplateParameters} params passed to the template
20 | * @returns {boolean} should it promisify callbacks
21 | */
22 | export function shouldPromisifyCallbacks(params) {
23 | return params.promisifyReplyCallback;
24 | }
25 |
26 | export function toCamelCase(string) {
27 | return _.camelCase(string);
28 | }
29 | export function toPascalCase(string) {
30 | string = _.camelCase(string);
31 | return string.charAt(0).toUpperCase() + string.slice(1);
32 | }
33 | export function toKebabCase(string) {
34 | return _.kebabCase(string);
35 | }
36 |
37 | /**
38 | * Returns the schema file name
39 | *
40 | * @param {string} schemaName
41 | * @returns
42 | */
43 | export function getSchemaFileName(schemaName) {
44 | return FormatHelpers.toPascalCase(schemaName);
45 | }
46 |
47 | /**
48 | * Figure out if our message content type or default content type matches a given payload.
49 | *
50 | * @param {string} messageContentType to check against payload
51 | * @param {string} defaultContentType to check against payload
52 | * @param {string} payload to check
53 | */
54 | function containsPayload(messageContentType, defaultContentType, payload) {
55 | if (
56 | (messageContentType !== undefined &&
57 | messageContentType.toLowerCase() === payload) ||
58 | (defaultContentType !== undefined && defaultContentType === payload)
59 | ) {
60 | return true;
61 | }
62 | return false;
63 | }
64 | export function isBinaryPayload(messageContentType, defaultContentType) {
65 | return containsPayload(
66 | messageContentType,
67 | defaultContentType,
68 | contentTypeBinary
69 | );
70 | }
71 | export function isStringPayload(messageContentType, defaultContentType) {
72 | return containsPayload(
73 | messageContentType,
74 | defaultContentType,
75 | contentTypeString
76 | );
77 | }
78 | export function isJsonPayload(messageContentType, defaultContentType) {
79 | return containsPayload(
80 | messageContentType,
81 | defaultContentType,
82 | contentTypeJSON
83 | );
84 | }
85 |
86 | /**
87 | * Checks if the message payload is of type null
88 | *
89 | * @param {Schema} messagePayload to check
90 | * @returns {boolean} does the payload contain null type
91 | */
92 | export function messageHasNotNullPayload(messagePayload) {
93 | return `${messagePayload.type()}` !== 'null';
94 | }
95 |
96 | /**
97 | * Get message type ensure that the correct message type is returned.
98 | *
99 | * @param {Message} message to find the message type for
100 | */
101 | export function getMessageType(message) {
102 | if (`${message.payload().type()}` === 'null') {
103 | return 'null';
104 | }
105 | return `${getSchemaFileName(message.payload().uid())}`;
106 | }
107 |
108 | /**
109 | * Convert JSON schema draft 7 types to typescript types
110 | * @param {*} jsonSchemaType
111 | * @param {*} property
112 | */
113 | export function toCType(jsonSchemaType, property) {
114 | switch (jsonSchemaType.toLowerCase()) {
115 | case 'string':
116 | return 'String';
117 | case 'integer':
118 | return 'int';
119 | case 'number':
120 | return 'decimal';
121 | case 'boolean':
122 | return 'bool';
123 | case 'object':
124 | if (property) {
125 | return `${property.uid()}Schema`;
126 | }
127 | return 'object';
128 |
129 | default:
130 | return 'object';
131 | }
132 | }
133 |
134 | /**
135 | * Cast JSON schema variable to csharp type
136 | *
137 | * @param {*} jsonSchemaType
138 | * @param {*} variableToCast
139 | */
140 | export function castToCType(jsonSchemaType, variableToCast) {
141 | switch (jsonSchemaType.toLowerCase()) {
142 | case 'string':
143 | return `$"{${variableToCast}}"`;
144 | case 'integer':
145 | return `int.Parse(${variableToCast})`;
146 | case 'number':
147 | return `decimal.Parse(${variableToCast}, System.Globalization.CultureInfo.InvariantCulture)`;
148 | case 'boolean':
149 | return `bool.Parse(${variableToCast})`;
150 | default:
151 | throw new Error(`Parameter type not supported - ${jsonSchemaType}`);
152 | }
153 | }
154 |
155 | /**
156 | * Realize parameters without using types without trailing comma
157 | */
158 | export function realizeParametersForChannelWithoutType(parameters) {
159 | let returnString = '';
160 | for (const [paramName] of parameters) {
161 | returnString += `${paramName},`;
162 | }
163 | if (returnString.length >= 1) {
164 | returnString = returnString.slice(0, -1);
165 | }
166 | return returnString;
167 | }
168 |
169 | /**
170 | * Realize parameters using types without trailing comma
171 | */
172 | export function realizeParametersForChannel(parameters, required = true) {
173 | let returnString = '';
174 | const requiredType = !required ? '?' : '';
175 | for (const parameter of parseParameters(parameters)) {
176 | returnString += `${parameter.csharpType}${requiredType} ${parameter.name} ${parameter.example},`;
177 | }
178 | if (returnString.length >= 1) {
179 | returnString = returnString.slice(0, -1);
180 | }
181 | return returnString;
182 | }
183 |
184 | export function parseParameters(parameters) {
185 | const params = [];
186 | for (const [paramName, parameter] of Object.entries(parameters)) {
187 | params.push({
188 | csharpType: toCType(parameter.schema().type()),
189 | name: paramName,
190 | example: parameter.extension('x-example'),
191 | });
192 | }
193 | return params;
194 | }
195 |
196 | export function cleanString(str) {
197 | return str.replace(/ {2}|\r\n|\n|\r/gm, '').trim();
198 | }
199 |
200 | export function getChannels(asyncapi) {
201 | const channels = asyncapi.channels();
202 |
203 | const createPublisher = (operation) => {
204 | return {
205 | operationId: toPascalCase(operation.id()),
206 | operationDescription: operation.description(),
207 | expiration: operation.hasBindings()
208 | ? operation.binding('amqp')['expiration']
209 | : 1000,
210 | userId: operation.hasBindings()
211 | ? operation.binding('amqp')['userId']
212 | : 'user',
213 | cc: operation.hasBindings() ? operation.binding('amqp')['cc'] : '',
214 | bcc: operation.hasBindings() ? operation.binding('amqp')['bcc'] : '',
215 | priority: operation.hasBindings()
216 | ? operation.binding('amqp')['priority']
217 | : 1,
218 | deliveryMode: operation.hasBindings()
219 | ? operation.binding('amqp')['deliveryMode']
220 | : '',
221 | mandatory: operation.hasBindings()
222 | ? operation.binding('amqp')['mandatory']
223 | : true,
224 | replyTo: operation.hasBindings()
225 | ? operation.binding('amqp')['replyTo']
226 | : '',
227 | timestamp: operation.hasBindings()
228 | ? operation.binding('amqp')['timestamp']
229 | : '',
230 | ack: operation.hasBindings() ? operation.binding('amqp')['ack'] : true,
231 | messageType: toPascalCase(
232 | operation._json && operation._json.message
233 | ? operation._json.message.name
234 | : ''
235 | ),
236 | };
237 | };
238 |
239 | const createSubscriber = (operation) => {
240 | return {
241 | operationId: toPascalCase(operation.id()),
242 | operationDescription: operation.description(),
243 | messageType: toPascalCase(
244 | operation._json && operation._json.message
245 | ? operation._json.message.name
246 | : ''
247 | ),
248 | };
249 | };
250 |
251 | return Object.entries(channels)
252 | .map(([channelName, channel]) => {
253 | const channelBinding = channel.hasBindings()
254 | ? channel.binding('amqp')
255 | : {};
256 |
257 | const defaultQueue = {
258 | name: '',
259 | 'x-prefetch-count': 100,
260 | 'x-confirm': false,
261 | };
262 |
263 | const defaultExchange = {
264 | name: '',
265 | type: 'topic',
266 | durable: true,
267 | autoDelete: false,
268 | 'x-alternate-exchange': '',
269 | vhost: '/',
270 | };
271 |
272 | const queue = channelBinding.queue ? channelBinding.queue : defaultQueue;
273 | const exchange = channelBinding.exchange
274 | ? channelBinding.exchange
275 | : defaultExchange;
276 |
277 | return {
278 | routingKey: channelName,
279 | publisher: channel.hasPublish()
280 | ? createPublisher(channel.publish())
281 | : undefined,
282 | subscriber: channel.hasSubscribe()
283 | ? createSubscriber(channel.subscribe())
284 | : undefined,
285 | queue: queue ? queue.name : '',
286 | prefetchCount: queue ? queue['x-prefetch-count'] : 0,
287 | confirm: queue ? queue['x-confirm'] : false,
288 | exchange: exchange ? exchange.name : '',
289 | exchangeType: exchange ? exchange.type : 'topic',
290 | vhost: exchange ? exchange.vhost : '/',
291 | isDurable: exchange ? exchange.durable : true,
292 | isAutoDelete: exchange ? exchange.autoDelete : false,
293 | alternateExchange: exchange ? exchange['x-alternate-exchange'] : '',
294 | };
295 | })
296 | .filter((publisher) => publisher);
297 | }
298 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
--------------------------------------------------------------------------------
/.github/workflows/notify-tsc-members-mention.yml:
--------------------------------------------------------------------------------
1 | # This action is centrally managed in https://github.com/asyncapi/.github/
2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo
3 |
4 | # This action notifies community on slack whenever there is a new issue, PR or discussion started in given repository
5 | name: Notify slack and email subscribers whenever TSC members are mentioned in GitHub
6 |
7 | on:
8 | issue_comment:
9 | types:
10 | - created
11 |
12 | discussion_comment:
13 | types:
14 | - created
15 |
16 | issues:
17 | types:
18 | - opened
19 |
20 | pull_request_target:
21 | types:
22 | - opened
23 |
24 | discussion:
25 | types:
26 | - created
27 |
28 | jobs:
29 | issue:
30 | if: github.event_name == 'issues' && contains(github.event.issue.body, '@asyncapi/tsc_members')
31 | name: TSC notification on every new issue
32 | runs-on: ubuntu-latest
33 | steps:
34 | - name: Checkout repository
35 | uses: actions/checkout@v4
36 | - name: Setup Node.js
37 | uses: actions/setup-node@v4
38 | with:
39 | node-version: 16
40 | cache: 'npm'
41 | cache-dependency-path: '**/package-lock.json'
42 | #########
43 | # Handling Slack notifications
44 | #########
45 | - name: Convert markdown to slack markdown
46 | # This workflow is from our own org repo and safe to reference by 'master'.
47 | uses: asyncapi/.github/.github/actions/slackify-markdown@master # //NOSONAR
48 | id: issuemarkdown
49 | with:
50 | markdown: "[${{github.event.issue.title}}](${{github.event.issue.html_url}}) \n ${{github.event.issue.body}}"
51 | - name: Send info about issue
52 | uses: rtCamp/action-slack-notify@c33737706dea87cd7784c687dadc9adf1be59990 # Using v2.3.2
53 | env:
54 | SLACK_WEBHOOK: ${{secrets.SLACK_TSC_MEMBERS_NOTIFY}}
55 | SLACK_TITLE: 🆘 New issue that requires TSC Members attention 🆘
56 | SLACK_MESSAGE: ${{steps.issuemarkdown.outputs.text}}
57 | MSG_MINIMAL: true
58 | #########
59 | # Handling Mailchimp notifications
60 | #########
61 | - name: Install deps
62 | run: npm install
63 | working-directory: ./.github/workflows/scripts/mailchimp
64 | - name: Send email with MailChimp
65 | uses: actions/github-script@v7
66 | env:
67 | CALENDAR_ID: ${{ secrets.CALENDAR_ID }}
68 | CALENDAR_SERVICE_ACCOUNT: ${{ secrets.CALENDAR_SERVICE_ACCOUNT }}
69 | MAILCHIMP_API_KEY: ${{ secrets.MAILCHIMP_API_KEY }}
70 | TITLE: ${{ github.event.issue.title }}
71 | with:
72 | script: |
73 | const sendEmail = require('./.github/workflows/scripts/mailchimp/index.js');
74 | sendEmail('${{github.event.issue.html_url}}', process.env.TITLE);
75 |
76 | pull_request:
77 | if: github.event_name == 'pull_request_target' && contains(github.event.pull_request.body, '@asyncapi/tsc_members')
78 | name: TSC notification on every new pull request
79 | runs-on: ubuntu-latest
80 | steps:
81 | - name: Checkout repository
82 | uses: actions/checkout@v4
83 | - name: Setup Node.js
84 | uses: actions/setup-node@v4
85 | with:
86 | node-version: 16
87 | cache: 'npm'
88 | cache-dependency-path: '**/package-lock.json'
89 | #########
90 | # Handling Slack notifications
91 | #########
92 | - name: Convert markdown to slack markdown
93 | # This workflow is from our own org repo and safe to reference by 'master'.
94 | uses: asyncapi/.github/.github/actions/slackify-markdown@master # //NOSONAR
95 | id: prmarkdown
96 | with:
97 | markdown: "[${{github.event.pull_request.title}}](${{github.event.pull_request.html_url}}) \n ${{github.event.pull_request.body}}"
98 | - name: Send info about pull request
99 | uses: rtCamp/action-slack-notify@c33737706dea87cd7784c687dadc9adf1be59990 # Using v2.3.2
100 | env:
101 | SLACK_WEBHOOK: ${{secrets.SLACK_TSC_MEMBERS_NOTIFY}}
102 | SLACK_TITLE: 🆘 New PR that requires TSC Members attention 🆘
103 | SLACK_MESSAGE: ${{steps.prmarkdown.outputs.text}}
104 | MSG_MINIMAL: true
105 | #########
106 | # Handling Mailchimp notifications
107 | #########
108 | - name: Install deps
109 | run: npm install
110 | working-directory: ./.github/workflows/scripts/mailchimp
111 | - name: Send email with MailChimp
112 | uses: actions/github-script@v7
113 | env:
114 | CALENDAR_ID: ${{ secrets.CALENDAR_ID }}
115 | CALENDAR_SERVICE_ACCOUNT: ${{ secrets.CALENDAR_SERVICE_ACCOUNT }}
116 | MAILCHIMP_API_KEY: ${{ secrets.MAILCHIMP_API_KEY }}
117 | TITLE: ${{ github.event.pull_request.title }}
118 | with:
119 | script: |
120 | const sendEmail = require('./.github/workflows/scripts/mailchimp/index.js');
121 | sendEmail('${{github.event.pull_request.html_url}}', process.env.TITLE);
122 |
123 | discussion:
124 | if: github.event_name == 'discussion' && contains(github.event.discussion.body, '@asyncapi/tsc_members')
125 | name: TSC notification on every new discussion
126 | runs-on: ubuntu-latest
127 | steps:
128 | - name: Checkout repository
129 | uses: actions/checkout@v4
130 | - name: Setup Node.js
131 | uses: actions/setup-node@v4
132 | with:
133 | node-version: 16
134 | cache: 'npm'
135 | cache-dependency-path: '**/package-lock.json'
136 | #########
137 | # Handling Slack notifications
138 | #########
139 | - name: Convert markdown to slack markdown
140 | # This workflow is from our own org repo and safe to reference by 'master'.
141 | uses: asyncapi/.github/.github/actions/slackify-markdown@master # //NOSONAR
142 | id: discussionmarkdown
143 | with:
144 | markdown: "[${{github.event.discussion.title}}](${{github.event.discussion.html_url}}) \n ${{github.event.discussion.body}}"
145 | - name: Send info about pull request
146 | uses: rtCamp/action-slack-notify@c33737706dea87cd7784c687dadc9adf1be59990 # Using v2.3.2
147 | env:
148 | SLACK_WEBHOOK: ${{secrets.SLACK_TSC_MEMBERS_NOTIFY}}
149 | SLACK_TITLE: 🆘 New discussion that requires TSC Members attention 🆘
150 | SLACK_MESSAGE: ${{steps.discussionmarkdown.outputs.text}}
151 | MSG_MINIMAL: true
152 | #########
153 | # Handling Mailchimp notifications
154 | #########
155 | - name: Install deps
156 | run: npm install
157 | working-directory: ./.github/workflows/scripts/mailchimp
158 | - name: Send email with MailChimp
159 | uses: actions/github-script@v7
160 | env:
161 | CALENDAR_ID: ${{ secrets.CALENDAR_ID }}
162 | CALENDAR_SERVICE_ACCOUNT: ${{ secrets.CALENDAR_SERVICE_ACCOUNT }}
163 | MAILCHIMP_API_KEY: ${{ secrets.MAILCHIMP_API_KEY }}
164 | TITLE: ${{ github.event.discussion.title }}
165 | with:
166 | script: |
167 | const sendEmail = require('./.github/workflows/scripts/mailchimp/index.js');
168 | sendEmail('${{github.event.discussion.html_url}}', process.env.TITLE);
169 |
170 | issue_comment:
171 | if: ${{ github.event_name == 'issue_comment' && !github.event.issue.pull_request && contains(github.event.comment.body, '@asyncapi/tsc_members') }}
172 | name: TSC notification on every new comment in issue
173 | runs-on: ubuntu-latest
174 | steps:
175 | - name: Checkout repository
176 | uses: actions/checkout@v4
177 | - name: Setup Node.js
178 | uses: actions/setup-node@v4
179 | with:
180 | node-version: 16
181 | cache: 'npm'
182 | cache-dependency-path: '**/package-lock.json'
183 | #########
184 | # Handling Slack notifications
185 | #########
186 | - name: Convert markdown to slack markdown
187 | # This workflow is from our own org repo and safe to reference by 'master'.
188 | uses: asyncapi/.github/.github/actions/slackify-markdown@master # //NOSONAR
189 | id: issuemarkdown
190 | with:
191 | markdown: "[${{github.event.issue.title}}](${{github.event.comment.html_url}}) \n ${{github.event.comment.body}}"
192 | - name: Send info about issue comment
193 | uses: rtCamp/action-slack-notify@c33737706dea87cd7784c687dadc9adf1be59990 # Using v2.3.2
194 | env:
195 | SLACK_WEBHOOK: ${{secrets.SLACK_TSC_MEMBERS_NOTIFY}}
196 | SLACK_TITLE: 🆘 New comment under existing issue that requires TSC Members attention 🆘
197 | SLACK_MESSAGE: ${{steps.issuemarkdown.outputs.text}}
198 | MSG_MINIMAL: true
199 | #########
200 | # Handling Mailchimp notifications
201 | #########
202 | - name: Install deps
203 | run: npm install
204 | working-directory: ./.github/workflows/scripts/mailchimp
205 | - name: Send email with MailChimp
206 | uses: actions/github-script@v7
207 | env:
208 | CALENDAR_ID: ${{ secrets.CALENDAR_ID }}
209 | CALENDAR_SERVICE_ACCOUNT: ${{ secrets.CALENDAR_SERVICE_ACCOUNT }}
210 | MAILCHIMP_API_KEY: ${{ secrets.MAILCHIMP_API_KEY }}
211 | TITLE: ${{ github.event.issue.title }}
212 | with:
213 | script: |
214 | const sendEmail = require('./.github/workflows/scripts/mailchimp/index.js');
215 | sendEmail('${{github.event.comment.html_url}}', process.env.TITLE);
216 |
217 | pr_comment:
218 | if: github.event_name == 'issue_comment' && github.event.issue.pull_request && contains(github.event.comment.body, '@asyncapi/tsc_members')
219 | name: TSC notification on every new comment in pr
220 | runs-on: ubuntu-latest
221 | steps:
222 | - name: Checkout repository
223 | uses: actions/checkout@v4
224 | - name: Setup Node.js
225 | uses: actions/setup-node@v4
226 | with:
227 | node-version: 16
228 | cache: 'npm'
229 | cache-dependency-path: '**/package-lock.json'
230 | #########
231 | # Handling Slack notifications
232 | #########
233 | - name: Convert markdown to slack markdown
234 | # This workflow is from our own org repo and safe to reference by 'master'.
235 | uses: asyncapi/.github/.github/actions/slackify-markdown@master # //NOSONAR
236 | id: prmarkdown
237 | with:
238 | markdown: "[${{github.event.issue.title}}](${{github.event.comment.html_url}}) \n ${{github.event.comment.body}}"
239 | - name: Send info about PR comment
240 | uses: rtCamp/action-slack-notify@c33737706dea87cd7784c687dadc9adf1be59990 # Using v2.3.2
241 | env:
242 | SLACK_WEBHOOK: ${{secrets.SLACK_TSC_MEMBERS_NOTIFY}}
243 | SLACK_TITLE: 🆘 New comment under existing PR that requires TSC Members attention 🆘
244 | SLACK_MESSAGE: ${{steps.prmarkdown.outputs.text}}
245 | MSG_MINIMAL: true
246 | #########
247 | # Handling Mailchimp notifications
248 | #########
249 | - name: Install deps
250 | run: npm install
251 | working-directory: ./.github/workflows/scripts/mailchimp
252 | - name: Send email with MailChimp
253 | uses: actions/github-script@v7
254 | env:
255 | CALENDAR_ID: ${{ secrets.CALENDAR_ID }}
256 | CALENDAR_SERVICE_ACCOUNT: ${{ secrets.CALENDAR_SERVICE_ACCOUNT }}
257 | MAILCHIMP_API_KEY: ${{ secrets.MAILCHIMP_API_KEY }}
258 | TITLE: ${{ github.event.issue.title }}
259 | with:
260 | script: |
261 | const sendEmail = require('./.github/workflows/scripts/mailchimp/index.js');
262 | sendEmail('${{github.event.comment.html_url}}', process.env.TITLE);
263 |
264 | discussion_comment:
265 | if: github.event_name == 'discussion_comment' && contains(github.event.comment.body, '@asyncapi/tsc_members')
266 | name: TSC notification on every new comment in discussion
267 | runs-on: ubuntu-latest
268 | steps:
269 | - name: Checkout repository
270 | uses: actions/checkout@v4
271 | - name: Setup Node.js
272 | uses: actions/setup-node@v4
273 | with:
274 | node-version: 16
275 | cache: 'npm'
276 | cache-dependency-path: '**/package-lock.json'
277 | #########
278 | # Handling Slack notifications
279 | #########
280 | - name: Convert markdown to slack markdown
281 | # This workflow is from our own org repo and safe to reference by 'master'.
282 | uses: asyncapi/.github/.github/actions/slackify-markdown@master # //NOSONAR
283 | id: discussionmarkdown
284 | with:
285 | markdown: "[${{github.event.discussion.title}}](${{github.event.comment.html_url}}) \n ${{github.event.comment.body}}"
286 | - name: Send info about discussion comment
287 | uses: rtCamp/action-slack-notify@c33737706dea87cd7784c687dadc9adf1be59990 # Using v2.3.2
288 | env:
289 | SLACK_WEBHOOK: ${{secrets.SLACK_TSC_MEMBERS_NOTIFY}}
290 | SLACK_TITLE: 🆘 New comment under existing discussion that requires TSC Members attention 🆘
291 | SLACK_MESSAGE: ${{steps.discussionmarkdown.outputs.text}}
292 | MSG_MINIMAL: true
293 | #########
294 | # Handling Mailchimp notifications
295 | #########
296 | - name: Install deps
297 | run: npm install
298 | working-directory: ./.github/workflows/scripts/mailchimp
299 | - name: Send email with MailChimp
300 | uses: actions/github-script@v7
301 | env:
302 | CALENDAR_ID: ${{ secrets.CALENDAR_ID }}
303 | CALENDAR_SERVICE_ACCOUNT: ${{ secrets.CALENDAR_SERVICE_ACCOUNT }}
304 | MAILCHIMP_API_KEY: ${{ secrets.MAILCHIMP_API_KEY }}
305 | TITLE: ${{ github.event.discussion.title }}
306 | with:
307 | script: |
308 | const sendEmail = require('./.github/workflows/scripts/mailchimp/index.js');
309 | sendEmail('${{github.event.comment.html_url}}', process.env.TITLE);
310 |
--------------------------------------------------------------------------------
/.github/workflows/scripts/mailchimp/htmlContent.js:
--------------------------------------------------------------------------------
1 | /**
2 | * This code is centrally managed in https://github.com/asyncapi/.github/
3 | * Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo
4 | */
5 | module.exports = (link, title) => {
6 |
7 | return `
8 |
9 |
10 |
11 |
19 |
20 |
21 |
22 | *|MC:SUBJECT|*
23 |
24 |
350 |
351 |
352 | *|MC_PREVIEW_TEXT|*
353 |
354 |
355 |
356 |
357 |
358 |
359 |
364 |
365 |
366 |
405 |
406 |
407 |
408 |
409 |
410 |
411 |
412 |
413 |
417 |
418 |
421 |
422 |
423 |
424 |
425 |
426 | Cheers,
427 | AsyncAPI Initiative
428 | |
429 |
430 |
431 |
434 |
435 |
439 | |
440 |
441 |
442 | |
443 |
444 |
445 |
480 |
481 |
482 |
487 |
488 | |
489 |
490 |
491 |
492 |
493 |
494 | `
495 | }
--------------------------------------------------------------------------------