diff --git a/Documents/Docs/Developer/Azure API V1.1_1.html b/Documents/Docs/Developer/Azure API V1.1_1.html new file mode 100644 index 0000000..7443d28 --- /dev/null +++ b/Documents/Docs/Developer/Azure API V1.1_1.html @@ -0,0 +1,2266 @@ + + + + + +مستند فنی | اندپوینت‌های مدیریت گیت و ورک‌آیتم‌ها در Azure DevOps + + + +
+
+
+
+ +
+
+
شماره مستند: TECH-AZD-1405-002
+
نسخه: ۱.۰
+
تاریخ تهیه: آذر ۱۴۰۵
+
طبقه‌بندی: فنی - داخلی
+
+
+
+TECHNICAL DOCUMENTATION +

اندپوینت‌های مدیریت گیت و ورک‌آیتم‌ها در Azure DevOps

+

راهنمای جامع پیاده‌سازی با C# - مدل‌های ورودی و خروجی

+
+
+
+
+توسعه‌دهنده گرامی،
+این مستند فنی، مرجع کاملی از تمامی اندپوینت‌های REST API مربوط به مدیریت مخازن Git و مدیریت Work Item‌ها (ایشوها) در Azure DevOps Server / Azure DevOps Services ارائه می‌دهد. هر اندپوینت به همراه متد HTTP، URL، مدل‌های ورودی (Request) و خروجی (Response) و نمونه کد C# تشریح شده است. نسخه API مورد استفاده: 7.1 می‌باشد. +
+ +
+
+
۱
+
+

پیش‌نیازها و احراز هویت

+
Prerequisites & Authentication
+
+
+
+

قبل از استفاده از هر اندپوینت، باید احراز هویت و ساختار پایه را تنظیم کنید:

+ +
+🔑 ساختار پایه URL:
+https://dev.azure.com/{organization}/{project}/_apis/... +
+ +
+

نمونه کد C# - تنظیم HttpClient با PAT

+
using System.Net.Http.Headers; +using System.Text; + +public class AzureDevOpsClient : IDisposable +{ + private readonly HttpClient _httpClient; + private readonly string _baseUrl; + + public AzureDevOpsClient(string organization, string project, string pat) + { + _baseUrl = $"https://dev.azure.com/{organization}/{project}"; + _httpClient = new HttpClient(); + _httpClient.DefaultRequestHeaders.Authorization = + new AuthenticationHeaderValue("Basic", + Convert.ToBase64String( + Encoding.ASCII.GetBytes($":{pat}"))); + _httpClient.DefaultRequestHeaders.Accept.Add( + new MediaTypeWithQualityHeaderValue("application/json")); + } + + public void Dispose() => _httpClient?.Dispose(); +}
+
+ +
+
+
Git Repos
API
+
مدیریت مخازن، برنچ‌ها و سیاست‌ها
+
+
+
Work Items
API
+
مدیریت ایشوها، روابط و کوئری‌ها
+
+
+
API
7.1
+
نسخه مورد استفاده در این مستند
+
+
+
+
+ + +
+
+
۲
+
+

مدیریت مخازن گیت (Git Repositories)

+
Git Repositories Management Endpoints
+
+
+
+

در این بخش، تمامی اندپوینت‌های مربوط به مدیریت مخازن گیت در Azure DevOps ارائه شده است:

+ + +
+

GET دریافت لیست مخازن

+
GET {baseUrl}/_apis/git/repositories?api-version=7.1
+

دریافت لیست تمام مخازن در یک پروژه. پارامترهای اختیاری: includeAllUrls, includeHidden, includeLinks

+ +
+
مدل خروجی (Response)
+
public class GitRepositoryListResponse +{ + public int Count { get; set; } + public List<GitRepository> Value { get; set; } +} + +public class GitRepository +{ + public Guid Id { get; set; } + public string Name { get; set; } + public string Url { get; set; } + public ProjectReference Project { get; set; } + public string DefaultBranch { get; set; } + public long Size { get; set; } + public string RemoteUrl { get; set; } + public string SshUrl { get; set; } + public string WebUrl { get; set; } + public bool IsDisabled { get; set; } + public bool IsInMaintenance { get; set; } +} + +public class ProjectReference +{ + public Guid Id { get; set; } + public string Name { get; set; } + public string Url { get; set; } + public string State { get; set; } + public string Visibility { get; set; } +}
+
+ +
+
نمونه کد C#
+
public async Task<GitRepositoryListResponse> GetRepositoriesAsync() +{ + var response = await _httpClient.GetAsync( + $"{_baseUrl}/_apis/git/repositories?api-version=7.1"); + response.EnsureSuccessStatusCode(); + return await response.Content + .ReadAsAsync<GitRepositoryListResponse>(); +}
+
+
+ + +
+

GET دریافت جزئیات یک مخزن

+
GET {baseUrl}/_apis/git/repositories/{repositoryId}?api-version=7.1
+

دریافت اطلاعات یک مخزن خاص با استفاده از ID یا نام مخزن. پارامترهای اختیاری: includeAllUrls, includeHidden, includeLinks

+ +
+
پارامترهای ورودی
+ + + + + + + + +
پارامترنوعاجباریتوضیح
repositoryIdstring / Guidبلهشناسه یا نام مخزن
includeAllUrlsboolخیرشامل تمام آدرس‌های دسترسی
includeHiddenboolخیرشامل مخازن مخفی
includeLinksboolخیرشامل لینک‌های مرتبط
+
+ +
+
مدل خروجی (Response)
+
// همان مدل GitRepository در بالا +public async Task<GitRepository> GetRepositoryAsync(string repositoryId) +{ + var response = await _httpClient.GetAsync( + $"{_baseUrl}/_apis/git/repositories/{repositoryId}?api-version=7.1"); + response.EnsureSuccessStatusCode(); + return await response.Content.ReadAsAsync<GitRepository>(); +}
+
+
+ + +
+

POST ایجاد مخزن جدید

+
POST {baseUrl}/_apis/git/repositories?api-version=7.1
+ +
+
مدل ورودی (Request Body)
+
public class CreateGitRepositoryRequest +{ + public string Name { get; set; } + public ProjectReference Project { get; set; } + public GitRepositoryRef ParentRepository { get; set; } // اختیاری - برای fork +} + +public class GitRepositoryRef +{ + public Guid Id { get; set; } + public string Name { get; set; } +}
+
+ +
+
مدل خروجی (Response) - همان GitRepository
+
public async Task<GitRepository> CreateRepositoryAsync(string name) +{ + var request = new CreateGitRepositoryRequest + { + Name = name, + Project = new ProjectReference { Name = _projectName } + }; + + var content = new StringContent( + JsonSerializer.Serialize(request), + Encoding.UTF8, "application/json"); + + var response = await _httpClient.PostAsync( + $"{_baseUrl}/_apis/git/repositories?api-version=7.1", content); + response.EnsureSuccessStatusCode(); + return await response.Content.ReadAsAsync<GitRepository>(); +}
+
+
+ + +
+

PATCH به‌روزرسانی مخزن

+
PATCH {baseUrl}/_apis/git/repositories/{repositoryId}?api-version=7.1
+

تغییر نام، تغییر برنچ پیش‌فرض، غیرفعال‌سازی یا فعال‌سازی مخزن

+ +
+
مدل ورودی (Request Body)
+
public class UpdateGitRepositoryRequest +{ + public string Name { get; set; } + public string DefaultBranch { get; set; } // مثال: "refs/heads/main" + public bool? IsDisabled { get; set; } + public bool? IsInMaintenance { get; set; } +}
+
+ +
+
نمونه کد C#
+
public async Task<GitRepository> UpdateRepositoryAsync( + string repositoryId, UpdateGitRepositoryRequest request) +{ + var content = new StringContent( + JsonSerializer.Serialize(request), + Encoding.UTF8, "application/json"); + + var httpRequest = new HttpRequestMessage( + HttpMethod.Patch, + $"{_baseUrl}/_apis/git/repositories/{repositoryId}?api-version=7.1") + { Content = content }; + + var response = await _httpClient.SendAsync(httpRequest); + response.EnsureSuccessStatusCode(); + return await response.Content.ReadAsAsync<GitRepository>(); +}
+
+
+ + +
+

DELETE حذف مخزن

+
DELETE {baseUrl}/_apis/git/repositories/{repositoryId}?api-version=7.1
+ +
+
نمونه کد C#
+
public async Task DeleteRepositoryAsync(string repositoryId) +{ + var response = await _httpClient.DeleteAsync( + $"{_baseUrl}/_apis/git/repositories/{repositoryId}?api-version=7.1"); + response.EnsureSuccessStatusCode(); + // Response: 204 No Content +}
+
+
+⚠️ هشدار: حذف مخزن غیرقابل بازگشت است. تمام تاریخچه کامیت‌ها، برنچ‌ها و تگ‌ها حذف خواهند شد. +
+
+ + +
+

GET دریافت آمار مخزن

+
GET {baseUrl}/_apis/git/repositories/{repositoryId}/stats?api-version=7.1
+ +
+
مدل خروجی (Response)
+
public class GitRepositoryStats +{ + public GitRepositoryStatsCommitCount CommitCount { get; set; } + public GitRepositoryStatsBranches Branches { get; set; } + public GitRepositoryStatsPullRequests PullRequests { get; set; } +} + +public class GitRepositoryStatsCommitCount +{ + public int Total { get; set; } +} + +public class GitRepositoryStatsBranches +{ + public int Count { get; set; } +}
+
+
+
+
+ + +
+
+
۳
+
+

مدیریت برنچ‌ها و Refs در گیت

+
Git Branches & Refs Management
+
+
+
+ + +
+

GET دریافت لیست برنچ‌ها

+
GET {baseUrl}/_apis/git/repositories/{repositoryId}/refs?api-version=7.1
+

پارامترهای اختیاری: filter (مثلاً "heads/"), filterContains, includeStatuses, includeMyBranches, latestStatusesOnly, top, skip

+ +
+
مدل خروجی (Response)
+
public class GitRefListResponse +{ + public int Count { get; set; } + public List<GitRef> Value { get; set; } +} + +public class GitRef +{ + public string Name { get; set; } // "refs/heads/main" + public string ObjectId { get; set; } // SHA of latest commit + public string Creator { get; set; } + public string Url { get; set; } + public List<GitStatus> Statuses { get; set; } + public bool IsLockedBy { get; set; } +}
+
+
+ + +
+

GET دریافت آمار برنچ‌ها

+
GET {baseUrl}/_apis/git/repositories/{repositoryId}/stats/branches?api-version=7.1
+

پارامتر اختیاری: name (نام برنچ برای فیلتر)

+ +
+
مدل خروجی (Response)
+
public class GitBranchStatsListResponse +{ + public int Count { get; set; } + public List<GitBranchStats> Value { get; set; } +} + +public class GitBranchStats +{ + public string Name { get; set; } + public int AheadCount { get; set; } + public int BehindCount { get; set; } + public GitCommitRef Commit { get; set; } + public bool IsBaseVersion { get; set; } +} + +public class GitCommitRef +{ + public string CommitId { get; set; } + public string Comment { get; set; } + public DateTime Committer { get; set; } + public GitUserDate Author { get; set; } + public List<string> Parents { get; set; } +} + +public class GitUserDate +{ + public string Name { get; set; } + public string Email { get; set; } + public DateTime Date { get; set; } +}
+
+
+ + +
+

POST ایجاد برنچ جدید

+
POST {baseUrl}/_apis/git/repositories/{repositoryId}/refs?api-version=7.1
+ +
+
مدل ورودی (Request Body)
+
public class GitRefUpdate +{ + public string Name { get; set; } // "refs/heads/new-branch" + public string NewObjectId { get; set; } // SHA commit to point to + public string OldObjectId { get; set; } // برای ایجاد: "0000000000000000000000000000000000000000" +} + +// آرایه‌ای از GitRefUpdate ارسال می‌شود
+
+ +
+
مدل خروجی (Response)
+
public class GitRefUpdateResult +{ + public string Name { get; set; } + public string NewObjectId { get; set; } + public string OldObjectId { get; set; } + public bool IsLocked { get; set; } + public string UpdateStatus { get; set; } // "succeeded", "rejected" + public string RepositoryId { get; set; } +}
+
+ +
+
نمونه کد C#
+
public async Task<GitRefUpdateResult> CreateBranchAsync( + string repositoryId, string branchName, string sourceCommitId) +{ + var refUpdates = new[] + { + new GitRefUpdate + { + Name = $"refs/heads/{branchName}", + NewObjectId = sourceCommitId, + OldObjectId = "0000000000000000000000000000000000000000" + } + }; + + var content = new StringContent( + JsonSerializer.Serialize(refUpdates), + Encoding.UTF8, "application/json"); + + var response = await _httpClient.PostAsync( + $"{_baseUrl}/_apis/git/repositories/{repositoryId}/refs?api-version=7.1", content); + response.EnsureSuccessStatusCode(); + var results = await response.Content.ReadAsAsync<List<GitRefUpdateResult>>(); + return results.FirstOrDefault(); +}
+
+
+ + +
+

POST حذف برنچ (با استفاده از Refs Update)

+
POST {baseUrl}/_apis/git/repositories/{repositoryId}/refs?api-version=7.1
+ +
+
مدل ورودی (حذف برنچ)
+
// برای حذف، NewObjectId را صفر قرار دهید +var refUpdates = new[] +{ + new GitRefUpdate + { + Name = $"refs/heads/{branchName}", + NewObjectId = "0000000000000000000000000000000000000000", + OldObjectId = currentCommitId // SHA فعلی برنچ + } +};
+
+
+ + +
+

PATCH قفل/باز کردن برنچ

+
PATCH {baseUrl}/_apis/git/repositories/{repositoryId}/refs?api-version=7.1&filter=heads/{branchName}
+ +
+
مدل ورودی (Request Body)
+
public class GitRefUpdateLock +{ + public bool IsLocked { get; set; } +}
+
+
+ + +
+

GET دریافت سیاست‌های برنچ

+
GET {baseUrl}/_apis/policy/configurations?api-version=7.1
+

دریافت تمام سیاست‌های تعریف شده (شامل سیاست‌های برنچ). پارامتر اختیاری: scope

+ +
+
مدل خروجی (Response)
+
public class PolicyConfigurationListResponse +{ + public int Count { get; set; } + public List<PolicyConfiguration> Value { get; set; } +} + +public class PolicyConfiguration +{ + public int Id { get; set; } + public PolicyType Type { get; set; } + public bool IsEnabled { get; set; } + public bool IsBlocking { get; set; } + public bool IsDeleted { get; set; } + public object Settings { get; set; } // JSON - بسته به نوع سیاست + public IdentityRef CreatedBy { get; set; } + public DateTime CreatedDate { get; set; } +} + +public class PolicyType +{ + public Guid Id { get; set; } + public string DisplayName { get; set; } +}
+
+
+ + +
+

POST ایجاد سیاست برنچ

+
POST {baseUrl}/_apis/policy/configurations?api-version=7.1
+ +
+
مدل ورودی (نمونه: سیاست حداقل تعداد بازبینی)
+
public class CreatePolicyConfigurationRequest +{ + public bool IsEnabled { get; set; } + public bool IsBlocking { get; set; } + public PolicyTypeRef Type { get; set; } + public BranchPolicySettings Settings { get; set; } +} + +public class PolicyTypeRef +{ + public Guid Id { get; set; } + // Minimum number of reviewers: "fa4e907d-c16b-4a4c-9dfa-4906e5d171dd" + // Build validation: "0609b952-1397-4640-95ec-e00a01b2c241" +} + +public class BranchPolicySettings +{ + public List<PolicyScope> Scope { get; set; } + public int MinimumApproverCount { get; set; } + public int CreatorVoteCountBehaviour { get; set; } + public bool AllowDownvotes { get; set; } + public bool ResetOnSourcePush { get; set; } +} + +public class PolicyScope +{ + public string RepositoryId { get; set; } + public string RefName { get; set; } // "refs/heads/main" + public string MatchKind { get; set; } // "Exact", "Prefix" +}
+
+
+
+
+ + +
+
+
۴
+
+

مدیریت آیتم‌ها، کامیت‌ها و پول‌ریکوئست‌ها در گیت

+
Git Items, Commits & Pull Requests
+
+
+
+ + +
+

GET دریافت آیتم‌های مخزن (فایل‌ها و پوشه‌ها)

+
GET {baseUrl}/_apis/git/repositories/{repositoryId}/items?api-version=7.1
+

پارامترها: path, recursionLevel (None, OneLevel, Full), includeContentMetadata, latestProcessedChange, download, includeContent, versionDescriptor.version, versionDescriptor.versionType

+ +
+
مدل خروجی (Response)
+
public class GitItemListResponse +{ + public int Count { get; set; } + public List<GitItem> Value { get; set; } +} + +public class GitItem +{ + public string ObjectId { get; set; } + public GitObjectType GitObjectType { get; set; } // "blob", "tree", "commit" + public VersionControlProjectInfo CommitOrBranch { get; set; } + public DateTime Date { get; set; } + public string Path { get; set; } + public string Url { get; set; } + public string Content { get; set; } // اگر includeContent=true + public string IsFolder { get; set; } +}
+
+
+ + +
+

GET دریافت لیست کامیت‌ها

+
GET {baseUrl}/_apis/git/repositories/{repositoryId}/commits?api-version=7.1
+

پارامترها: searchCriteria.itemVersion.version, searchCriteria.compareVersion.version, searchCriteria.fromDate, searchCriteria.toDate, searchCriteria.itemPath, searchCriteria.author, searchCriteria.$top, searchCriteria.$skip, searchCriteria.includeWorkItems, searchCriteria.includeUser, searchCriteria.includeStatuses, searchCriteria.historyMode

+ +
+
مدل خروجی (Response)
+
public class GitCommitListResponse +{ + public int Count { get; set; } + public List<GitCommitRef> Value { get; set; } +} + +// GitCommitRef قبلاً تعریف شده + فیلدهای اضافی: +public class GitCommitRefExtended +{ + public string CommitId { get; set; } + public string Comment { get; set; } + public bool CommentTruncated { get; set; } + public GitUserDate Author { get; set; } + public GitUserDate Committer { get; set; } + public List<string> Parents { get; set; } + public List<string> WorkItems { get; set; } + public string Url { get; set; } + public GitChangeCounts ChangeCounts { get; set; } +} + +public class GitChangeCounts +{ + public int Add { get; set; } + public int Edit { get; set; } + public int Delete { get; set; } +}
+
+
+ + +
+

GET دریافت لیست پول‌ریکوئست‌ها

+
GET {baseUrl}/_apis/git/repositories/{repositoryId}/pullRequests?api-version=7.1
+

پارامترها: searchCriteria.status (active, completed, abandoned, all), searchCriteria.creatorId, searchCriteria.reviewerId, searchCriteria.sourceRefName, searchCriteria.targetRefName, searchCriteria.includeLinks, $top, $skip

+ +
+
مدل خروجی (Response)
+
public class GitPullRequestListResponse +{ + public int Count { get; set; } + public List<GitPullRequest> Value { get; set; } +} + +public class GitPullRequest +{ + public int PullRequestId { get; set; } + public int CodeReviewId { get; set; } + public string Status { get; set; } // "active", "completed", "abandoned" + public IdentityRef CreatedBy { get; set; } + public DateTime CreationDate { get; set; } + public DateTime? ClosedDate { get; set; } + public string Title { get; set; } + public string Description { get; set; } + public string SourceRefName { get; set; } + public string TargetRefName { get; set; } + public string MergeStatus { get; set; } + public bool SupportsIterations { get; set; } + public GitRepository Repository { get; set; } + public string Url { get; set; } +}
+
+
+ + +
+

POST ایجاد پول‌ریکوئست جدید

+
POST {baseUrl}/_apis/git/repositories/{repositoryId}/pullRequests?api-version=7.1
+ +
+
مدل ورودی (Request Body)
+
public class CreatePullRequestRequest +{ + public string SourceRefName { get; set; } // "refs/heads/feature-branch" + public string TargetRefName { get; set; } // "refs/heads/main" + public string Title { get; set; } + public string Description { get; set; } + public bool IsDraft { get; set; } + public List<IdentityRef> Reviewers { get; set; } + public List<WorkItemRef> WorkItemReferences { get; set; } +} + +public class IdentityRef +{ + public string Id { get; set; } + public string DisplayName { get; set; } + public string UniqueName { get; set; } +}
+
+
+ + +
+

PATCH تکمیل (Merge) پول‌ریکوئست

+
PATCH {baseUrl}/_apis/git/repositories/{repositoryId}/pullRequests/{pullRequestId}?api-version=7.1
+ +
+
مدل ورودی (Request Body)
+
public class CompletePullRequestRequest +{ + public string Status { get; set; } // "completed" + public GitPullRequestCompletionOptions CompletionOptions { get; set; } + public string LastMergeSourceCommit { get; set; } +} + +public class GitPullRequestCompletionOptions +{ + public bool DeleteSourceBranch { get; set; } + public string MergeCommitMessage { get; set; } + public bool SquashMerge { get; set; } + public bool AutoCompleteSetBy { get; set; } + public bool BypassPolicy { get; set; } + public string TransitionWorkItemsTo { get; set; } +}
+
+
+
+
+ + +
+
+
۵
+
+

مدیریت ورک‌آیتم‌ها (ایشوها)

+
Work Items Management Endpoints
+
+
+
+

در این بخش، تمامی اندپوینت‌های مربوط به مدیریت Work Item‌ها (معادل ایشوها) در Azure DevOps ارائه شده است. این شامل ایجاد، ویرایش، حذف، کوئری، روابط و کامنت‌ها می‌باشد.

+ + +
+

POST ایجاد ورک‌آیتم جدید

+
POST {baseUrl}/_apis/wit/workitems/${workItemType}?api-version=7.1
+

مقدار workItemType می‌تواند: Bug, Task, User Story, Feature, Epic, Issue باشد. پارامترهای اختیاری: validateOnly, bypassRules, suppressNotifications, expand

+ +
+
مدل ورودی (Request Body) - JSON Patch
+
// Content-Type: application/json-patch+json +public class JsonPatchDocument : List<JsonPatchOperation> { } + +public class JsonPatchOperation +{ + public string Op { get; set; } // "add", "remove", "replace", "move", "copy", "test" + public string Path { get; set; } // "/fields/System.Title" + public object Value { get; set; } + public string From { get; set; } // برای move و copy +}
+
+ +
+
نمونه کد C# - ایجاد Bug
+
public async Task<WorkItem> CreateBugAsync( + string title, string description, string priority) +{ + var patchDocument = new JsonPatchDocument + { + new JsonPatchOperation + { + Op = "add", + Path = "/fields/System.Title", + Value = title + }, + new JsonPatchOperation + { + Op = "add", + Path = "/fields/System.Description", + Value = description + }, + new JsonPatchOperation + { + Op = "add", + Path = "/fields/Microsoft.VSTS.Common.Priority", + Value = priority // "1", "2", "3", "4" + }, + new JsonPatchOperation + { + Op = "add", + Path = "/fields/System.Tags", + Value = "backend; critical" + } + }; + + var content = new StringContent( + JsonSerializer.Serialize(patchDocument), + Encoding.UTF8, "application/json-patch+json"); + + var response = await _httpClient.PostAsync( + $"{_baseUrl}/_apis/wit/workitems/$Bug?api-version=7.1", content); + response.EnsureSuccessStatusCode(); + return await response.Content.ReadAsAsync<WorkItem>(); +}
+
+ +
+
مدل خروجی (Response)
+
public class WorkItem +{ + public int Id { get; set; } + public int Rev { get; set; } + public Dictionary<string, object> Fields { get; set; } + public WorkItemRelations Relations { get; set; } + public Dictionary<string, object> Links { get; set; } + public string Url { get; set; } +} + +// فیلدهای رایج در Dictionary: +// "System.Id", "System.Title", "System.State", "System.WorkItemType" +// "System.AssignedTo", "System.CreatedBy", "System.CreatedDate" +// "System.Description", "System.Tags", "System.AreaPath" +// "Microsoft.VSTS.Common.Priority", "Microsoft.VSTS.Common.Severity" +// "Microsoft.VSTS.Scheduling.StoryPoints", "Microsoft.VSTS.Common.State"
+
+
+ + +
+

GET دریافت یک ورک‌آیتم

+
GET {baseUrl}/_apis/wit/workitems/{workItemId}?api-version=7.1
+

پارامترهای اختیاری: $expand (relations, fields, all), fields (لیست فیلدها با کاما جدا شده), asOf, expand

+ +
+
پارامترهای ورودی
+ + + + + + + + +
پارامترنوعاجباریتوضیح
workItemIdintبلهشناسه ورک‌آیتم
$expandstringخیرrelations, fields, all
fieldsstringخیرلیست فیلدهای درخواستی (کاما جدا شده)
asOfDateTimeخیردریافت وضعیت در تاریخ خاص
+
+ +
+
نمونه کد C#
+
public async Task<WorkItem> GetWorkItemAsync( + int workItemId, string expand = "all") +{ + var response = await _httpClient.GetAsync( + $"{_baseUrl}/_apis/wit/workitems/{workItemId}?$expand={expand}&api-version=7.1"); + response.EnsureSuccessStatusCode(); + return await response.Content.ReadAsAsync<WorkItem>(); +}
+
+
+ + +
+

GET دریافت چند ورک‌آیتم همزمان

+
GET {baseUrl}/_apis/wit/workitems?ids={ids}&api-version=7.1
+

پارامترها: ids (لیست شناسه‌ها با کاما جدا شده، حداکثر ۲۰۰), $expand, fields, asOf, errorPolicy

+ +
+
مدل خروجی (Response)
+
public class WorkItemListResponse +{ + public int Count { get; set; } + public List<WorkItem> Value { get; set; } +}
+
+
+ + +
+

PATCH به‌روزرسانی ورک‌آیتم

+
PATCH {baseUrl}/_apis/wit/workitems/{workItemId}?api-version=7.1
+

پارامترهای اختیاری: validateOnly, bypassRules, suppressNotifications, $expand

+ +
+
مدل ورودی (Request Body) - JSON Patch
+
// Content-Type: application/json-patch+json +public async Task<WorkItem> UpdateWorkItemAsync( + int workItemId, Dictionary<string, object> fieldsToUpdate) +{ + var patchDocument = new JsonPatchDocument(); + + foreach (var field in fieldsToUpdate) + { + patchDocument.Add(new JsonPatchOperation + { + Op = "add", // یا "replace" + Path = $"/fields/{field.Key}", + Value = field.Value + }); + } + + var content = new StringContent( + JsonSerializer.Serialize(patchDocument), + Encoding.UTF8, "application/json-patch+json"); + + var httpRequest = new HttpRequestMessage( + HttpMethod.Patch, + $"{_baseUrl}/_apis/wit/workitems/{workItemId}?api-version=7.1") + { Content = content }; + + var response = await _httpClient.SendAsync(httpRequest); + response.EnsureSuccessStatusCode(); + return await response.Content.ReadAsAsync<WorkItem>(); +} + +// مثال استفاده: +var updated = await UpdateWorkItemAsync(123, new Dictionary<string, object> +{ + { "System.State", "Resolved" }, + { "Microsoft.VSTS.Common.ResolvedReason", "Fixed" }, + { "System.AssignedTo", "user@example.com" } +});
+
+
+ + +
+

DELETE حذف ورک‌آیتم

+
DELETE {baseUrl}/_apis/wit/workitems/{workItemId}?api-version=7.1
+

پارامتر اختیاری: destroy (حذف دائمی بدون امکان بازیابی), suppressNotifications

+ +
+
نمونه کد C#
+
public async Task<WorkItemDelete> DeleteWorkItemAsync( + int workItemId, bool destroy = false) +{ + var url = $"{_baseUrl}/_apis/wit/workitems/{workItemId}?api-version=7.1"; + if (destroy) url += "&destroy=true"; + + var response = await _httpClient.DeleteAsync(url); + response.EnsureSuccessStatusCode(); + return await response.Content.ReadAsAsync<WorkItemDelete>(); +} + +public class WorkItemDelete +{ + public int Id { get; set; } + public int Code { get; set; } + public bool Deleted { get; set; } + public string Name { get; set; } + public string Type { get; set; } + public string Project { get; set; } +}
+
+
+ + +
+

PATCH مدیریت روابط ورک‌آیتم (لینک‌ها)

+
PATCH {baseUrl}/_apis/wit/workitems/{workItemId}?api-version=7.1
+ +
+
مدل ورودی - افزودن رابطه
+
// افزودن لینک بین دو ورک‌آیتم +var patchDocument = new JsonPatchDocument +{ + new JsonPatchOperation + { + Op = "add", + Path = "/relations/-", + Value = new + { + rel = "System.LinkTypes.Related", + url = $"{_baseUrl}/_apis/wit/workItems/{targetWorkItemId}", + attributes = new { comment = "Linked related work item" } + } + } +}; + +// انواع رایج روابط (rel): +// "System.LinkTypes.Related" - مرتبط +// "System.LinkTypes.Hierarchy-Forward" - فرزند +// "System.LinkTypes.Hierarchy-Reverse" - والد +// "System.LinkTypes.Dependency-Forward" - وابستگی (پس از) +// "System.LinkTypes.Dependency-Reverse" - وابستگی (قبل از) +// "ArtifactLink" - لینک به آرتیفکت (کامیت، PR و...) +// "ExternalLink" - لینک خارجی +// "Hyperlink" - هایپرلینک
+
+ +
+
مدل رابطه در خروجی
+
public class WorkItemRelations +{ + public List<WorkItemRelation> Relations { get; set; } +} + +public class WorkItemRelation +{ + public string Rel { get; set; } + public string Url { get; set; } + public Dictionary<string, object> Attributes { get; set; } +}
+
+
+ + +
+

POST افزودن کامنت به ورک‌آیتم

+
POST {baseUrl}/_apis/wit/workitems/{workItemId}/comments?api-version=7.1
+ +
+
مدل ورودی (Request Body)
+
public class WorkItemCommentCreateRequest +{ + public string Text { get; set; } // متن کامنت +} + +// مثال: +var commentRequest = new WorkItemCommentCreateRequest +{ + Text = "این مشکل در نسخه 2.1 برطرف شد. لطفاً تأیید کنید." +};
+
+ +
+
مدل خروجی (Response)
+
public class WorkItemComment +{ + public int Id { get; set; } + public int WorkItemId { get; set; } + public int Version { get; set; } + public string Text { get; set; } + public IdentityRef CreatedBy { get; set; } + public DateTime CreatedDate { get; set; } + public IdentityRef ModifiedBy { get; set; } + public DateTime ModifiedDate { get; set; } +}
+
+
+ + +
+

GET دریافت کامنت‌های ورک‌آیتم

+
GET {baseUrl}/_apis/wit/workitems/{workItemId}/comments?api-version=7.1
+

پارامترهای اختیاری: $top, $skip, order (asc, desc), expand (renderedText)

+ +
+
مدل خروجی (Response)
+
public class WorkItemCommentsListResponse +{ + public int TotalCount { get; set; } + public int Count { get; set; } + public int FromRevision { get; set; } + public List<WorkItemComment> Comments { get; set; } +}
+
+
+ + +
+

PATCH ویرایش کامنت ورک‌آیتم

+
PATCH {baseUrl}/_apis/wit/workitems/{workItemId}/comments/{commentId}?api-version=7.1
+ +
+
مدل ورودی (Request Body)
+
public class WorkItemCommentUpdateRequest +{ + public string Text { get; set; } +}
+
+
+ + +
+

DELETE حذف کامنت ورک‌آیتم

+
DELETE {baseUrl}/_apis/wit/workitems/{workItemId}/comments/{commentId}?api-version=7.1
+
+
نمونه کد
+
public async Task DeleteCommentAsync(int workItemId, int commentId) +{ + var response = await _httpClient.DeleteAsync( + $"{_baseUrl}/_apis/wit/workitems/{workItemId}/comments/{commentId}?api-version=7.1"); + response.EnsureSuccessStatusCode(); + // Response: 204 No Content +}
+
+
+
+
+ + +
+
+
۶
+
+

کوئری‌های پیشرفته (WIQL) و فیلدهای ورک‌آیتم

+
WIQL Queries & Work Item Fields
+
+
+
+ + +
+

POST اجرای کوئری WIQL

+
POST {baseUrl}/_apis/wit/wiql?api-version=7.1
+

زبان کوئری WIQL (Work Item Query Language) برای جستجوی پیشرفته ورک‌آیتم‌ها. پارامترهای اختیاری: $top, timePrecision

+ +
+
مدل ورودی (Request Body)
+
public class WiqlQueryRequest +{ + public string Query { get; set; } +} + +// نمونه کوئری WIQL: +var query = new WiqlQueryRequest +{ + Query = @" + SELECT [System.Id], [System.Title], [System.State], + [System.AssignedTo], [Microsoft.VSTS.Common.Priority] + FROM WorkItems + WHERE [System.WorkItemType] = 'Bug' + AND [System.State] <> 'Closed' + AND [System.AreaPath] UNDER 'MyProject\Backend' + ORDER BY [Microsoft.VSTS.Common.Priority] ASC, [System.CreatedDate] DESC" +};
+
+ +
+
مدل خروجی (Response)
+
public class WiqlQueryResponse +{ + public string QueryType { get; set; } // "flat", "tree", "oneHop" + public List<WorkItemReference> WorkItems { get; set; } + public Dictionary<string, string> Columns { get; set; } + public List<SortColumn> SortColumns { get; set; } +} + +public class WorkItemReference +{ + public int Id { get; set; } + public string Url { get; set; } +} + +public class SortColumn +{ + public string Field { get; set; } + public bool Descending { get; set; } +}
+
+ +
+
نمونه کد C# - اجرای کوئری و دریافت نتایج کامل
+
public async Task<List<WorkItem>> QueryWorkItemsAsync(string wiqlQuery) +{ + // مرحله ۱: اجرای کوئری + var queryRequest = new WiqlQueryRequest { Query = wiqlQuery }; + var queryContent = new StringContent( + JsonSerializer.Serialize(queryRequest), + Encoding.UTF8, "application/json"); + + var queryResponse = await _httpClient.PostAsync( + $"{_baseUrl}/_apis/wit/wiql?api-version=7.1", queryContent); + queryResponse.EnsureSuccessStatusCode(); + var queryResult = await queryResponse.Content.ReadAsAsync<WiqlQueryResponse>(); + + // مرحله ۲: دریافت جزئیات ورک‌آیتم‌ها (حداکثر ۲۰۰ در هر درخواست) + var workItemIds = queryResult.WorkItems.Select(w => w.Id).ToList(); + var workItems = new List<WorkItem>(); + + for (int i = 0; i < workItemIds.Count; i += 200) + { + var batch = workItemIds.Skip(i).Take(200); + var ids = string.Join(",", batch); + var response = await _httpClient.GetAsync( + $"{_baseUrl}/_apis/wit/workitems?ids={ids}&$expand=all&api-version=7.1"); + response.EnsureSuccessStatusCode(); + var result = await response.Content.ReadAsAsync<WorkItemListResponse>(); + workItems.AddRange(result.Value); + } + + return workItems; +}
+
+
+ + +
+

GET دریافت انواع ورک‌آیتم

+
GET {baseUrl}/_apis/wit/workitemtypes?api-version=7.1
+ +
+
مدل خروجی (Response)
+
public class WorkItemTypeListResponse +{ + public int Count { get; set; } + public List<WorkItemType> Value { get; set; } +} + +public class WorkItemType +{ + public string Name { get; set; } // "Bug", "Task", "User Story" + public string ReferenceName { get; set; } + public string Description { get; set; } + public string Color { get; set; } + public string Icon { get; set; } + public bool IsDisabled { get; set; } + public List<WorkItemTypeStateInfo> States { get; set; } + public Dictionary<string, string> XmlEncodedFieldStates { get; set; } +} + +public class WorkItemTypeStateInfo +{ + public string Name { get; set; } // "New", "Active", "Resolved", "Closed" + public string Color { get; set; } + public string Category { get; set; } // "Proposed", "InProgress", "Resolved", "Completed" +}
+
+
+ + +
+

GET دریافت فیلدهای ورک‌آیتم

+
GET {baseUrl}/_apis/wit/fields?api-version=7.1
+ +
+
مدل خروجی (Response)
+
public class WorkItemFieldListResponse +{ + public int Count { get; set; } + public List<WorkItemField> Value { get; set; } +} + +public class WorkItemField +{ + public string Name { get; set; } + public string ReferenceName { get; set; } // "System.Title" + public string Type { get; set; } // "string", "integer", "dateTime", "boolean", "html" + public bool ReadOnly { get; set; } + public bool IsIdentity { get; set; } + public bool IsPicklist { get; set; } + public string Usage { get; set; } // "workItem", "tree", "extension" + public string Description { get; set; } + public List<string> SupportedOperations { get; set; } +}
+
+
+ + +
+

GET دریافت تاریخچه تغییرات ورک‌آیتم

+
GET {baseUrl}/_apis/wit/workitems/{workItemId}/revisions?api-version=7.1
+

پارامترهای اختیاری: $top, $skip, $expand (fields, relations)

+ +
+
مدل خروجی (Response)
+
public class WorkItemRevisionListResponse +{ + public int Count { get; set; } + public List<WorkItemRevision> Value { get; set; } +} + +public class WorkItemRevision +{ + public int Id { get; set; } + public int Rev { get; set; } + public Dictionary<string, object> Fields { get; set; } + public WorkItemRelations Relations { get; set; } + public string Url { get; set; } +}
+
+
+ + +
+

GET دریافت آپدیت‌های ورک‌آیتم

+
GET {baseUrl}/_apis/wit/workitems/{workItemId}/updates?api-version=7.1
+

پارامترهای اختیاری: $top, $skip, $expand. تفاوت با Revisions: هر آپدیت شامل فیلدهای تغییر یافته است.

+ +
+
مدل خروجی (Response)
+
public class WorkItemUpdateListResponse +{ + public int Count { get; set; } + public List<WorkItemUpdate> Value { get; set; } +} + +public class WorkItemUpdate +{ + public int Id { get; set; } + public int WorkItemId { get; set; } + public int Rev { get; set; } + public IdentityRef RevisedBy { get; set; } + public DateTime RevisedDate { get; set; } + public Dictionary<string, WorkItemFieldUpdate> Fields { get; set; } + public WorkItemRelationUpdates Relations { get; set; } + public string Url { get; set; } +} + +public class WorkItemFieldUpdate +{ + public object OldValue { get; set; } + public object NewValue { get; set; } +} + +public class WorkItemRelationUpdates +{ + public List<WorkItemRelation> Added { get; set; } + public List<WorkItemRelation> Removed { get; set; } + public List<WorkItemRelation> Updated { get; set; } +}
+
+
+ + +
+

GET دریافت ورک‌آیتم‌های حذف شده (Recycle Bin)

+
GET {baseUrl}/_apis/wit/recyclebin?api-version=7.1
+

پارامترهای اختیاری: $top, $skip, project

+ +
+
مدل خروجی (Response)
+
public class WorkItemDeleteListResponse +{ + public int Count { get; set; } + public List<WorkItemDeleteReference> Value { get; set; } +} + +public class WorkItemDeleteReference +{ + public int Id { get; set; } + public string Name { get; set; } + public string Type { get; set; } + public string Project { get; set; } + public bool Deleted { get; set; } + public IdentityRef DeletedBy { get; set; } + public DateTime DeletedDate { get; set; } + public string Code { get; set; } + public string Message { get; set; } +}
+
+
+ + +
+

PATCH بازیابی ورک‌آیتم حذف شده

+
PATCH {baseUrl}/_apis/wit/recyclebin/{workItemId}?api-version=7.1
+ +
+
مدل ورودی (Request Body)
+
public class WorkItemDeleteUpdate +{ + public bool IsDeleted { get; set; } // false برای بازیابی +} + +// مثال: +var restoreRequest = new WorkItemDeleteUpdate { IsDeleted = false };
+
+
+ + +
+

GET دریافت تگ‌های ورک‌آیتم

+
GET {baseUrl}/_apis/wit/workitems/{workItemId}/tags?api-version=7.1
+ +
+
مدل خروجی (Response)
+
public class WorkItemTagListResponse +{ + public int Count { get; set; } + public List<WorkItemTag> Value { get; set; } +} + +public class WorkItemTag +{ + public Guid Id { get; set; } + public string Name { get; set; } + public string Url { get; set; } +}
+
+
+ + +
+

PUT افزودن تگ به ورک‌آیتم

+
PUT {baseUrl}/_apis/wit/workitems/{workItemId}/tags/{tagNameOrId}?api-version=7.1
+
+
نمونه کد C#
+
public async Task AddTagToWorkItemAsync(int workItemId, string tagName) +{ + var content = new StringContent("", Encoding.UTF8, "application/json"); + var response = await _httpClient.PutAsync( + $"{_baseUrl}/_apis/wit/workitems/{workItemId}/tags/{tagName}?api-version=7.1", + content); + response.EnsureSuccessStatusCode(); +}
+
+
+ + +
+

DELETE حذف تگ از ورک‌آیتم

+
DELETE {baseUrl}/_apis/wit/workitems/{workItemId}/tags/{tagNameOrId}?api-version=7.1
+
+
نمونه کد C#
+
public async Task RemoveTagFromWorkItemAsync(int workItemId, string tagName) +{ + var response = await _httpClient.DeleteAsync( + $"{_baseUrl}/_apis/wit/workitems/{workItemId}/tags/{tagName}?api-version=7.1"); + response.EnsureSuccessStatusCode(); +}
+
+
+
+
+ + +
+
+
۷
+
+

مدیریت پیوست‌ها (Attachments)

+
Work Item Attachments Management
+
+
+
+ + +
+

POST آپلود پیوست

+
POST {baseUrl}/_apis/wit/attachments?fileName={fileName}&api-version=7.1
+

پارامتر اختیاری: areaPath. Content-Type باید application/octet-stream باشد.

+ +
+
نمونه کد C#
+
public async Task<AttachmentReference> UploadAttachmentAsync( + byte[] fileContent, string fileName) +{ + var content = new ByteArrayContent(fileContent); + content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); + + var response = await _httpClient.PostAsync( + $"{_baseUrl}/_apis/wit/attachments?fileName={fileName}&api-version=7.1", + content); + response.EnsureSuccessStatusCode(); + return await response.Content.ReadAsAsync<AttachmentReference>(); +} + +public class AttachmentReference +{ + public Guid Id { get; set; } + public string Url { get; set; } +}
+
+ +
+
لینک کردن پیوست به ورک‌آیتم
+
// پس از آپلود، باید پیوست را به ورک‌آیتم لینک کنید +var patchDocument = new JsonPatchDocument +{ + new JsonPatchOperation + { + Op = "add", + Path = "/relations/-", + Value = new + { + rel = "AttachedFile", + url = attachmentReference.Url, // از مرحله آپلود + attributes = new { comment = "فایل گزارش خطا" } + } + } +};
+
+
+ + +
+

GET دریافت پیوست

+
GET {baseUrl}/_apis/wit/attachments/{attachmentId}?api-version=7.1
+

پارامتر اختیاری: download (true برای دانلود فایل)

+ +
+
نمونه کد C#
+
public async Task<byte[]> DownloadAttachmentAsync(Guid attachmentId) +{ + var response = await _httpClient.GetAsync( + $"{_baseUrl}/_apis/wit/attachments/{attachmentId}?download=true&api-version=7.1"); + response.EnsureSuccessStatusCode(); + return await response.Content.ReadAsByteArrayAsync(); +}
+
+
+
+
+ + +
+
+
۸
+
+

جدول خلاصه تمامی اندپوینت‌ها

+
Complete Endpoints Summary
+
+
+
+ +

الف) اندپوینت‌های مدیریت گیت:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
عملیاتمتداندپوینتتوضیح
لیست مخازنGET/git/repositoriesدریافت تمام مخازن پروژه
جزئیات مخزنGET/git/repositories/{id}دریافت اطلاعات یک مخزن
ایجاد مخزنPOST/git/repositoriesایجاد مخزن جدید
ویرایش مخزنPATCH/git/repositories/{id}تغییر نام، برنچ پیش‌فرض
حذف مخزنDELETE/git/repositories/{id}حذف مخزن
آمار مخزنGET/git/repositories/{id}/statsآمار کامیت و برنچ
لیست RefsGET/git/repositories/{id}/refsلیست برنچ‌ها و تگ‌ها
ایجاد/حذف برنچPOST/git/repositories/{id}/refsایجاد یا حذف برنچ
آمار برنچGET/git/repositories/{id}/stats/branchesآمار برنچ‌ها
لیست آیتم‌هاGET/git/repositories/{id}/itemsفایل‌ها و پوشه‌ها
لیست کامیت‌هاGET/git/repositories/{id}/commitsتاریخچه کامیت‌ها
لیست PRهاGET/git/repositories/{id}/pullRequestsدریافت پول‌ریکوئست‌ها
ایجاد PRPOST/git/repositories/{id}/pullRequestsایجاد پول‌ریکوئست
تکمیل PRPATCH/git/repositories/{id}/pullRequests/{prId}Merge کردن
سیاست‌هاGET/policy/configurationsسیاست‌های برنچ
ایجاد سیاستPOST/policy/configurationsافزودن سیاست جدید
+ +

ب) اندپوینت‌های مدیریت ورک‌آیتم‌ها:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
عملیاتمتداندپوینتتوضیح
ایجاد ورک‌آیتمPOST/wit/workitems/${type}ایجاد Bug, Task, Issue و...
دریافت ورک‌آیتمGET/wit/workitems/{id}جزئیات یک ورک‌آیتم
دریافت چندتاییGET/wit/workitems?ids=حداکثر ۲۰۰ همزمان
ویرایش ورک‌آیتمPATCH/wit/workitems/{id}با JSON Patch
حذف ورک‌آیتمDELETE/wit/workitems/{id}حذف (موقت یا دائمی)
مدیریت روابطPATCH/wit/workitems/{id}/relations/-
افزودن کامنتPOST/wit/workitems/{id}/commentsثبت نظر
لیست کامنت‌هاGET/wit/workitems/{id}/commentsدریافت نظرات
ویرایش کامنتPATCH/wit/workitems/{id}/comments/{cid}ویرایش نظر
حذف کامنتDELETE/wit/workitems/{id}/comments/{cid}حذف نظر
کوئری WIQLPOST/wit/wiqlجستجوی پیشرفته
انواع ورک‌آیتمGET/wit/workitemtypesBug, Task, Issue و...
فیلدهاGET/wit/fieldsتمام فیلدهای موجود
تاریخچه (Revisions)GET/wit/workitems/{id}/revisionsنسخه‌های قبلی
آپدیت‌هاGET/wit/workitems/{id}/updatesتغییرات فیلدها
سطل بازیافتGET/wit/recyclebinورک‌آیتم‌های حذف شده
بازیابیPATCH/wit/recyclebin/{id}بازگرداندن از حذف
لیست تگ‌هاGET/wit/workitems/{id}/tagsتگ‌های ورک‌آیتم
افزودن تگPUT/wit/workitems/{id}/tags/{tag}افزودن تگ
حذف تگDELETE/wit/workitems/{id}/tags/{tag}حذف تگ
آپلود پیوستPOST/wit/attachmentsآپلود فایل
دریافت پیوستGET/wit/attachments/{id}دانلود فایل
+
+
+ + +
+
+
۹
+
+

کلاس سرویس یکپارچه C#

+
Complete AzureDevOps Service Implementation
+
+
+
+

در زیر یک کلاس سرویس کامل که تمام عملیات اصلی را پوشش می‌دهد ارائه شده است:

+ +
using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; + +public interface IAzureDevOpsService +{ + // Git Repository Operations + Task<List<GitRepository>> GetRepositoriesAsync(); + Task<GitRepository> GetRepositoryAsync(string repositoryId); + Task<GitRepository> CreateRepositoryAsync(string name); + Task<GitRepository> UpdateRepositoryAsync(string id, UpdateGitRepositoryRequest req); + Task DeleteRepositoryAsync(string repositoryId); + Task<List<GitRef>> GetBranchesAsync(string repositoryId); + Task<GitRefUpdateResult> CreateBranchAsync(string repoId, string branch, string commitId); + + // Work Item Operations + Task<WorkItem> CreateWorkItemAsync(string type, JsonPatchDocument patch); + Task<WorkItem> GetWorkItemAsync(int id, string expand = "all"); + Task<WorkItem> UpdateWorkItemAsync(int id, JsonPatchDocument patch); + Task DeleteWorkItemAsync(int id, bool destroy = false); + Task<List<WorkItem>> QueryWorkItemsAsync(string wiql); + Task<WorkItemComment> AddCommentAsync(int id, string text); +} + +public class AzureDevOpsService : IAzureDevOpsService, IDisposable +{ + private readonly HttpClient _http; + private readonly string _baseUrl; + private static readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull + }; + + public AzureDevOpsService(string org, string project, string pat) + { + _baseUrl = $"https://dev.azure.com/{org}/{project}"; + _http = new HttpClient(); + _http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( + "Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes($":{pat}"))); + _http.DefaultRequestHeaders.Accept.Add( + new MediaTypeWithQualityHeaderValue("application/json")); + } + + // === GIT REPOSITORY OPERATIONS === + public async Task<List<GitRepository>> GetRepositoriesAsync() + { + var res = await _http.GetAsync($"{_baseUrl}/_apis/git/repositories?api-version=7.1"); + res.EnsureSuccessStatusCode(); + var result = await res.Content.ReadFromJsonAsync<GitRepositoryListResponse>(_jsonOptions); + return result?.Value ?? new(); + } + + public async Task<GitRepository> CreateRepositoryAsync(string name) + { + var body = new { name }; + var res = await _http.PostAsJsonAsync($"{_baseUrl}/_apis/git/repositories?api-version=7.1", body, _jsonOptions); + res.EnsureSuccessStatusCode(); + return await res.Content.ReadFromJsonAsync<GitRepository>(_jsonOptions); + } + + public async Task DeleteRepositoryAsync(string repositoryId) + { + var res = await _http.DeleteAsync($"{_baseUrl}/_apis/git/repositories/{repositoryId}?api-version=7.1"); + res.EnsureSuccessStatusCode(); + } + + public async Task<List<GitRef>> GetBranchesAsync(string repositoryId) + { + var res = await _http.GetAsync( + $"{_baseUrl}/_apis/git/repositories/{repositoryId}/refs?filter=heads/&api-version=7.1"); + res.EnsureSuccessStatusCode(); + var result = await res.Content.ReadFromJsonAsync<GitRefListResponse>(_jsonOptions); + return result?.Value ?? new(); + } + + // === WORK ITEM OPERATIONS === + public async Task<WorkItem> CreateWorkItemAsync(string type, JsonPatchDocument patch) + { + var content = new StringContent( + JsonSerializer.Serialize(patch, _jsonOptions), + Encoding.UTF8, "application/json-patch+json"); + var res = await _http.PostAsync($"{_baseUrl}/_apis/wit/workitems/${type}?api-version=7.1", content); + res.EnsureSuccessStatusCode(); + return await res.Content.ReadFromJsonAsync<WorkItem>(_jsonOptions); + } + + public async Task<WorkItem> UpdateWorkItemAsync(int id, JsonPatchDocument patch) + { + var content = new StringContent( + JsonSerializer.Serialize(patch, _jsonOptions), + Encoding.UTF8, "application/json-patch+json"); + var request = new HttpRequestMessage(HttpMethod.Patch, + $"{_baseUrl}/_apis/wit/workitems/{id}?api-version=7.1") { Content = content }; + var res = await _http.SendAsync(request); + res.EnsureSuccessStatusCode(); + return await res.Content.ReadFromJsonAsync<WorkItem>(_jsonOptions); + } + + public async Task<WorkItemComment> AddCommentAsync(int id, string text) + { + var body = new { text }; + var res = await _http.PostAsJsonAsync( + $"{_baseUrl}/_apis/wit/workitems/{id}/comments?api-version=7.1", body, _jsonOptions); + res.EnsureSuccessStatusCode(); + return await res.Content.ReadFromJsonAsync<WorkItemComment>(_jsonOptions); + } + + public void Dispose() => _http?.Dispose(); +}
+ +
+✅ نکته مهم: برای استفاده از ReadFromJsonAsync و PostAsJsonAsync باید پکیج Microsoft.AspNetCore.Http.Extensions یا System.Net.Http.Json را نصب کنید. +
+
+
+ + +
+
+
۱۰
+
+

جمع‌بندی و نکات تکمیلی

+
Summary & Additional Notes
+
+
+
+ +
+

📋 خلاصه مستند

+

این مستند شامل ۱۶ اندپوینت مدیریت گیت و ۲۱ اندپوینت مدیریت ورک‌آیتم به همراه مدل‌های کامل ورودی/خروجی و نمونه کدهای کاربردی C# می‌باشد.

+
+💡 نکات کلیدی:
+• تمامی درخواست‌ها نیاز به احراز هویت با PAT یا OAuth دارند
+• نسخه API مورد استفاده: 7.1 (سازگار با Azure DevOps Services و Server 2022+)
+• برای ایجاد/ویرایش ورک‌آیتم از فرمت JSON Patch استفاده می‌شود
+• حداکثر ۲۰۰ ورک‌آیتم در هر درخواست دسته‌ای قابل دریافت است +
+
+ +
+📚 منابع تکمیلی: +
    +
  • Azure DevOps REST API Reference: https://learn.microsoft.com/en-us/rest/api/azure/devops/
  • +
  • Git Repositories API: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/repositories
  • +
  • Work Items API: https://learn.microsoft.com/en-us/rest/api/azure/devops/wit/work-items
  • +
  • WIQL Syntax: https://learn.microsoft.com/en-us/azure/devops/boards/queries/wiql-syntax
  • +
+
+ +
+⚠️ محدودیت‌ها (Rate Limits): +
    +
  • Azure DevOps Services: محدودیت نرخ بر اساس سازمان و کاربر
  • +
  • حداکثر ۲۰۰ ورک‌آیتم در هر درخواست GET دسته‌ای
  • +
  • حداکثر ۱۰۰۰ نتیجه در هر کوئری WIQL
  • +
  • برای عملیات حجیم، از صفحه‌بندی ($top و $skip) استفاده کنید
  • +
+
+
+
+ +
+این مستند فنی جهت استفاده تیم توسعه تهیه شده است. نسخه ۱.۰ | آذر ۱۴۰۵ +
+
+ +
+ + \ No newline at end of file diff --git a/Documents/Docs/Developer/Azure Extension Development v1.0.html b/Documents/Docs/Developer/Azure Extension Development v1.0.html new file mode 100644 index 0000000..d085a7e --- /dev/null +++ b/Documents/Docs/Developer/Azure Extension Development v1.0.html @@ -0,0 +1,967 @@ + + + + + +راهنمای کامل ساخت، تست و دیباگ افزونه Azure DevOps با iFrame + + + + +
+ +
+
+
+ +
+
+
شماره مستند: DEV-GUIDE-1405-003
+
نسخه: ۲.۰
+
تاریخ تهیه: آبان ۱۴۰۵
+
طبقه‌بندی: داخلی — تیم توسعه
+
+
+ +
+ END-TO-END DEVELOPMENT GUIDE +

راهنمای کامل ساخت، تست و دیباگ افزونه Azure DevOps

+

از SDK و webpack تا بارگذاری iFrame در محیط لوکال و واکشی داده‌ها

+
+
+ +
+ +
+ هدف این مستند:
+ این راهنما یک مسیر کامل و گام‌به‌گام از صفر تا اجرای موفق یک افزونه Azure DevOps در محیط لوکال است. شما یاد می‌گیرید چگونه SDK را به شکل صحیح مقداردهی کنید (و خطای AZDevOps is not defined را برای همیشه حل کنید)، webpack را با HTTPS پیکربندی کنید، افزونه را از طریق baseUri در iFrame بارگذاری کنید، و اطلاعات واقعی پروژه را از SDK دریافت نمایید. تمام کدهای نمونه و دستورات در جای خود قرار دارند تا مستقیماً قابل اجرا باشند. +
+ + + +
+
+
۱
+
+

پیش‌نیازها و ابزارهای محیط توسعه

+
Prerequisites & Toolchain
+
+
+
+

ابزارهای زیر را نصب کنید. نسخه‌های پیشنهادی در جدول آمده است:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ابزارنسخه پیشنهادیدلیل نیاز
Node.js۲۰ یا بالاترمحیط اجرای npm و webpack. عدم تطابق نسخه باعث خطاهای عجیب می‌شود.
Visual Studio Codeآخرین نسخهمحیط توسعه اصلی و دیباگر یکپارچه.
Firefoxآخرین نسخهدیباگر Chrome از iFrame پشتیبانی نمی‌کند؛ Firefox و افزونه Debugger for Firefox ضروری است[reference:0].
Debugger for Firefox (افزونه VS Code)آخرین نسخهاتصال Breakpoint در VS Code به کد داخل iFrame.
tfx-cliآخرین نسخهبسته‌بندی و انتشار افزونه. نصب با npm i -g tfx-cli[reference:1].
+ +
+ 📦 نصب سریع: +
npm install -g tfx-cli
+npm install -g webpack webpack-cli webpack-dev-server
+
+
+
+ + + +
+
+
۲
+
+

ساختار نهایی پروژه

+
Project Structure
+
+
+
+

ساختار پیشنهادی که در ادامه این مستند بر اساس آن پیش می‌رویم به شکل زیر است. این ساختار با نمونه رسمی مایکروسافت برای Hot Reload و Debug هم‌خوانی کامل دارد[reference:2]:

+ +
xUiExt/
+├── src/
+│   ├── index.ts              ← نقطه ورود افزونه (SDK را init می‌کند)
+│   └── index.html            ← قالب HTML افزونه (توسط CopyWebpackPlugin کپی می‌شود)
+├── configs/
+│   ├── dev.json              ← override مخصوص توسعه (baseUri = localhost)
+│   └── release.json          ← override مخصوص انتشار
+├── dist/                     ← خروجی webpack (خودکار)
+├── webpack.config.js
+├── vss-extension.json        ← manifest اصلی
+├── package.json
+└── tsconfig.json             ← در صورت استفاده از TypeScript
+ +
+ 💡 چرا configs/dev.json؟ مقدار baseUri نباید مستقیماً در manifest اصلی نوشته شود. با استفاده از فایل override و پارامتر --overrides-file، محیط توسعه و محیط نهایی از هم جدا می‌مانند و هنگام بسته‌بندی نهایی، خودکار حذف می‌شود[reference:3]. +
+
+
+ + + +
+
+
۳
+
+

راه‌اندازی پروژه و نصب وابستگی‌ها

+
Project Initialization & Dependencies
+
+
+
+
    +
  1. +
    ایجاد پروژه Node.js
    +

    در پوشه xUiExt دستور زیر را اجرا کنید:

    +
    npm init -y
    +
  2. +
  3. +
    نصب SDK و وابستگی‌های توسعه
    +

    SDK را از npm نصب کنید (روش توصیه‌شده برای جلوگیری از خطای AZDevOps is not defined):

    +
    npm install azure-devops-extension-sdk --save
    +npm install --save-dev webpack webpack-cli webpack-dev-server typescript ts-loader copy-webpack-plugin
    +

    اگر از JavaScript ساده استفاده می‌کنید، typescript و ts-loader را حذف کنید.

    +
  4. +
  5. +
    افزودن اسکریپت‌های کاربردی به package.json
    +

    در فایل package.json، بخش scripts را به شکل زیر ویرایش کنید:

    +
    "scripts": {
    +  "start:dev": "webpack serve --mode development --config webpack.config.js",
    +  "build:dev": "webpack --mode development",
    +  "package:dev": "tfx extension create --manifest-globs vss-extension.json --overrides-file configs/dev.json"
    +}
    +
  6. +
+
+
+ + + +
+
+
۴
+
+

یکپارچه‌سازی صحیح SDK (حل قطعی خطای AZDevOps is not defined)

+
SDK Integration & Initialization Pattern
+
+
+
+

خطای AZDevOps is not defined ریشه در دو اشتباه رایج دارد: (۱) بارگذاری SDK با تگ اسکریپت ساده و انتظار وجود یک متغیر سراسری، و (۲) اجرای کد افزونه پیش از آماده شدن SDK. راه‌حل استاندارد و پایدار، استفاده از بسته npm به همراه الگوی init → ready → getService است.

+ +
+ ❌ روش اشتباه (منشاء خطا): +
<script src="./js/SDK.min.js"></script>
+<script src="./js/app.js"></script>
+

در این حالت، app.js بلافاصله اجرا می‌شود و به متغیری به نام AZDevOps دسترسی ندارد، زیرا SDK به این شکل متغیر سراسری تعریف نمی‌کند.

+
+ +
+ ✓ روش صحیح (استفاده از npm و الگوی رسمی): +
+ +

الف) فایل src/index.ts (یا index.js)

+

SDK را import کرده و دقیقاً به این ترتیب مقداردهی کنید. الگوی زیر در تمام نمونه‌های رسمی مایکروسافت رعایت شده است[reference:4]:

+ +
// src/index.ts
+import * as SDK from "azure-devops-extension-sdk";
+import { CommonServiceIds, IProjectPageService } from "azure-devops-extension-api";
+
+async function initialize() {
+  // ۱. مقداردهی اولیه — همیشه اولین قدم
+  await SDK.init();
+
+  // ۲. انتظار برای آماده شدن SDK — قبل از هر فراخوانی دیگر
+  await SDK.ready();
+
+  // ۳. اکنون امن است که سرویس‌ها را فراخوانی کنید
+  const projectService = await SDK.getService<IProjectPageService>(
+    CommonServiceIds.ProjectPageService
+  );
+  const project = await projectService.getProject();
+
+  // ۴. نمایش نتیجه در صفحه
+  const el = document.getElementById("result");
+  if (el) {
+    el.textContent = `پروژه جاری: ${project?.name ?? "نامشخص"}`;
+  }
+
+  // ۵. اطلاع‌دادن به میزبان که بارگذاری کامل شد
+  SDK.notifyLoadSucceeded();
+}
+
+initialize().catch((err) => {
+  console.error("خطا در راه‌اندازی افزونه:", err);
+  const el = document.getElementById("result");
+  if (el) el.textContent = "خطا در اتصال به Azure DevOps";
+});
+ +
+ ⚠️ نکته حیاتی: هرگز SDK.getService را قبل از await SDK.ready() فراخوانی نکنید. تابع getService به‌طور خودکار منتظر ready() می‌ماند، اما صریح نوشتن آن باعث می‌شود ترتیب اجرا شفاف و خطاها قابل‌ردیابی باشد[reference:5]. +
+ +

ب) فایل src/index.html

+

این فایل به‌عنوان قالب HTML افزونه استفاده می‌شود. تگ اسکریپت SDK را حذف کنید؛ webpack خودش باندل را تزریق می‌کند:

+ +
<!DOCTYPE html>
+<html lang="fa" dir="rtl">
+<head>
+  <meta charset="UTF-8" />
+  <title>افزونه من</title>
+  <style>
+    body { font-family: 'Segoe UI', sans-serif; padding: 20px; }
+    #result { margin-top: 15px; font-weight: bold; color: #107c10; }
+  </style>
+</head>
+<body>
+  <h2>👋 سلام از افزونه من!</h2>
+  <p>اطلاعات پروژه جاری:</p>
+  <div id="result">در حال اتصال...</div>
+</body>
+</html>
+
+
+ + + +
+
+
۵
+
+

پیکربندی webpack با HTTPS و Hot Reload

+
Webpack Configuration for Local iFrame Testing
+
+
+
+

فایل webpack.config.js باید سه کار انجام دهد: باندل کردن کد، کپی کردن HTML به dist، و اجرای سرور HTTPS روی پورت ۳۰۰۰. پیکربندی زیر بر اساس نمونه رسمی Hot Reload مایکروسافت تنظیم شده است[reference:6][reference:7]:

+ +
const path = require("path");
+const CopyWebpackPlugin = require("copy-webpack-plugin");
+
+module.exports = {
+  mode: "development",
+  devtool: "inline-source-map", // برای دیباگ بهتر
+
+  entry: "./src/index.ts", // یا "./src/index.js"
+
+  output: {
+    path: path.resolve(__dirname, "dist"),
+    filename: "bundle.js",
+    publicPath: "/dist/", // حیاتی برای Hot Reload
+  },
+
+  resolve: {
+    extensions: [".ts", ".js"],
+  },
+
+  module: {
+    rules: [
+      {
+        test: /\.ts$/,
+        use: "ts-loader",
+        exclude: /node_modules/,
+      },
+    ],
+  },
+
+  plugins: [
+    new CopyWebpackPlugin({
+      patterns: [{ from: "**/*.html", context: "src" }],
+    }),
+  ],
+
+  devServer: {
+    server: { type: "https" }, // HTTPS الزامی برای iFrame
+    port: 3000,
+    hot: true,
+    static: {
+      directory: path.resolve(__dirname, "dist"),
+      publicPath: "/dist/",
+    },
+    headers: {
+      "Access-Control-Allow-Origin": "*",
+    },
+  },
+};
+ +
+ 🔍 چرا publicPath: "/dist/"؟ به‌طور پیش‌فرض webpack فایل‌ها را در ریشه localhost:3000 سرو می‌کند، اما افزونه به دنبال فایل‌ها در مسیر dist است. تنظیم publicPath روی /dist/ این ناهماهنگی را حل می‌کند و Hot Reload را فعال نگه می‌دارد[reference:8]. +
+ +

اگر از JavaScript خالص استفاده می‌کنید (بدون TypeScript)، بخش module.rules و ts-loader را حذف کنید و entry را به "./src/index.js" تغییر دهید.

+
+
+ + + +
+
+
۶
+
+

فایل Manifest و تنظیم baseUri برای iFrame

+
vss-extension.json & baseUri Override
+
+
+
+

فایل vss-extension.json هویت افزونه را تعریف می‌کند. نکته کلیدی برای تست لوکال، تنظیم baseUri از طریق فایل override است، نه در manifest اصلی.

+ +

الف) vss-extension.json (بدون baseUri)

+
{
+  "manifestVersion": 1,
+  "id": "my-local-extension",
+  "publisher": "my-publisher",
+  "version": "1.0.0",
+  "name": "My Local Extension",
+  "description": "تست افزونه در محیط لوکال",
+  "targets": [{ "id": "Microsoft.VisualStudio.Services" }],
+  "icons": { "default": "images/extension-icon.png" },
+  "contributions": [
+    {
+      "id": "my-hub",
+      "type": "ms.vss-web.hub",
+      "targets": ["ms.vss-web.project-hub-group"],
+      "properties": {
+        "name": "افزونه من",
+        "uri": "dist/index.html"
+      }
+    }
+  ],
+  "files": [
+    { "path": "dist", "addressable": true }
+  ]
+}
+ +
+ 📌 توجه: مقدار uri روی "dist/index.html" تنظیم شده تا با خروجی webpack هم‌خوان باشد. فایل‌های داخل dist با "addressable": true قابل دسترسی می‌شوند. +
+ +

ب) configs/dev.json (فایل Override مخصوص توسعه)

+

این فایل فقط هنگام ساخت نسخه توسعه استفاده می‌شود و baseUri را به سرور لوکال اشاره می‌دهد[reference:9]:

+ +
{
+  "id": "my-local-extension-dev",
+  "public": false,
+  "baseUri": "https://localhost:3000"
+}
+ +

هنگام بسته‌بندی نسخه توسعه، از دستور زیر استفاده کنید:

+
npm run package:dev
+

یا مستقیماً:

+
tfx extension create --manifest-globs vss-extension.json --overrides-file configs/dev.json
+ +
+ ✓ نتیجه: Azure DevOps منابع افزونه را به‌جای بسته VSIX، از https://localhost:3000 بارگذاری می‌کند. این یعنی هر تغییری در کد، بلافاصله در iFrame منعکس می‌شود، بدون نیاز به بسته‌بندی مجدد[reference:10]. +
+
+
+ + + +
+
+
۷
+
+

اجرا و بارگذاری در iFrame — گام‌به‌گام

+
Running the Dev Server & Loading in Azure DevOps
+
+
+
+
    +
  1. +
    اجرای سرور توسعه
    +

    در پوشه پروژه دستور زیر را اجرا کنید:

    +
    npm run start:dev
    +

    خروجی باید مشابه این باشد:

    +
    <i> [webpack-dev-server] Project is running at:
    +<i> [webpack-dev-server] Loopback: https://localhost:3000/, https://[::1]:3000/
    +
  2. +
  3. +
    پذیرش گواهی HTTPS در مرورگر
    +

    آدرس https://localhost:3000/dist/index.html را یک بار مستقیماً در Firefox باز کنید و هشدار گواهی خودامضا (Self-Signed) را بپذیرید. اگر این کار را نکنید، iFrame در Azure DevOps بارگذاری نخواهد شد.

    +
  4. +
  5. +
    بسته‌بندی و نصب نسخه توسعه
    +

    فایل VSIX مخصوص توسعه را بسازید:

    +
    npm run package:dev
    +

    سپس در Azure DevOps به Organization Settings → Extensions بروید، گزینه Shared یا Browse Marketplace را انتخاب کنید و فایل .vsix تولیدشده را آپلود و نصب نمایید.

    +
  6. +
  7. +
    فعال‌سازی دسترسی به شبکه داخلی (در صورت نیاز)
    +

    اگر مرورگر iFrame را به‌دلیل Private Network Access مسدود کرد، در Organization Settings → Policies گزینه “Allow extensions to access local network resources” را موقتاً فعال کنید[reference:11].

    +
  8. +
  9. +
    مشاهده افزونه در iFrame
    +

    به پروژه Azure DevOps خود بروید. در منوی Hubها، گزینه «افزونه من» را انتخاب کنید. iFrame باز می‌شود و صفحه شما از سرور لوکال بارگذاری می‌گردد. اکنون باید اطلاعات پروژه را ببینید.

    +
  10. +
+
+
+ + + +
+
+
۸
+
+

دیباگ Breakpoint در iFrame با VS Code و Firefox

+
Debugging Inside the iFrame
+
+
+
+

دیباگر Chrome در VS Code از iFrame پشتیبانی نمی‌کند؛ بنابراین از Firefox و افزونه Debugger for Firefox استفاده می‌کنیم[reference:12].

+ +

یک فایل .vscode/launch.json با محتوای زیر بسازید:

+ +
{
+  "version": "0.2.0",
+  "configurations": [
+    {
+      "name": "Launch Firefox against Azure DevOps",
+      "type": "firefox",
+      "request": "launch",
+      "url": "https://dev.azure.com/{your-org}/{your-project}",
+      "reAttach": true,
+      "pathMappings": [
+        {
+          "url": "webpack:///",
+          "path": "${workspaceFolder}/"
+        }
+      ]
+    }
+  ]
+}
+ +

سپس F5 را بزنید (مطمئن شوید npm run start:dev در حال اجراست). Breakpointها در فایل src/index.ts فعال می‌شوند و می‌توانید متغیرها را در VS Code بررسی کنید[reference:13].

+ +
+ 💡 گزینه جایگزین سریع: اگر نیازی به Breakpoint در VS Code ندارید، کافی است در کد خود بنویسید debugger;. با باز کردن DevTools مرورگر (F12) و انتخاب فریم iFrame افزونه از منوی context، اجرا در آن خط متوقف می‌شود. +
+
+
+ + + +
+
+
۹
+
+

واکشی داده‌های بیشتر از SDK

+
Fetching Data: User, Context & Extension Data
+
+
+
+

پس از await SDK.ready()، می‌توانید به طیف وسیعی از داده‌ها دسترسی داشته باشید. چند نمونه پرکاربرد:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
دادهکدتوضیح
اطلاعات کاربر جاریSDK.getUser()نام نمایشی، شناسه و ایمیل کاربر.
Context کامل افزونهSDK.getExtensionContext()شامل project، team، hub و سایر اطلاعات زمینه.
اطلاعات پروژهSDK.getService<IProjectPageService>(CommonServiceIds.ProjectPageService)سرویس رسمی برای دریافت پروژه جاری[reference:14].
داده‌های ذخیره‌شده افزونهSDK.getService<IExtensionDataService>(CommonServiceIds.ExtensionDataService)برای ذخیره و بازیابی تنظیمات افزونه[reference:15].
+ +

مثال کامل برای دریافت اطلاعات کاربر و پروژه به‌صورت هم‌زمان:

+ +
async function fetchData() {
+  await SDK.init();
+  await SDK.ready();
+
+  const user = SDK.getUser();
+  const projectService = await SDK.getService<IProjectPageService>(
+    CommonServiceIds.ProjectPageService
+  );
+  const project = await projectService.getProject();
+
+  document.getElementById("result")!.innerHTML = `
+    <p>کاربر: <strong>${user.displayName}</strong></p>
+    <p>پروژه: <strong>${project?.name}</strong></p>
+  `;
+
+  SDK.notifyLoadSucceeded();
+}
+ +
+ ⚠️ محدودیت iFrame: برخی APIهای مرورگر (مانند getDisplayMedia برای ضبط صفحه) در iFrame سندباکس مسدود هستند. اگر افزونه شما به چنین قابلیتی نیاز دارد، آن را در یک Pop-up سطح بالا باز کنید، نه داخل iFrame. +
+
+
+ + + +
+
+
۱۰
+
+

رفع اشکالات رایج

+
Troubleshooting Common Errors
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
خطاعلتراه‌حل
AZDevOps is not definedبارگذاری SDK با تگ اسکریپت و انتظار متغیر سراسریاز بسته npm و الگوی init → ready → getService استفاده کنید (بخش ۴).
Can't resolve './src'webpack فایل پیکربندی را پیدا نکرده و به پیش‌فرض برگشتهبا --config ./webpack.config.js اجرا کنید و وجود فایل را بررسی نمایید.
Unknown option '--https'حذف فلگ --https در webpack-cli جدیداز devServer: { server: { type: 'https' } } در فایل پیکربندی استفاده کنید.
iFrame بارگذاری نمی‌شود (صفحه سفید)عدم پذیرش گواهی HTTPS لوکال، یا فعال نبودن دسترسی شبکه داخلیابتدا https://localhost:3000/dist/index.html را در مرورگر باز و گواهی را بپذیرید؛ سپس سیاست Private Network Access را فعال کنید[reference:16].
SDK.getService مقدار undefined برمی‌گرداندفراخوانی قبل از ready() یا عدم انتظار برای Promiseهمیشه await SDK.ready() را قبل از getService قرار دهید و خروجی را await کنید[reference:17].
Hot Reload کار نمی‌کندتنظیم نبودن publicPath روی /dist/در output، مقدار publicPath: "/dist/" را تنظیم کنید[reference:18].
+
+
+ + + +
+
+
✓
+
+

جمع‌بندی و چک‌لیست نهایی

+
Final Checklist
+
+
+
+
+

🎯 مسیر کامل در یک نگاه

+

۱. SDK را از npm نصب و با الگوی await SDK.init(); await SDK.ready(); مقداردهی کنید.

+

۲. webpack را با server: { type: 'https' }، publicPath: "/dist/" و CopyWebpackPlugin پیکربندی کنید.

+

۳. baseUri را در configs/dev.json روی https://localhost:3000 تنظیم کنید.

+

۴. سرور را با npm run start:dev اجرا کنید و گواهی HTTPS را در مرورگر بپذیرید.

+

۵. VSIX توسعه را با npm run package:dev بسازید و در سازمان آپلود کنید.

+

۶. با Firefox + Debugger for Firefox در VS Code، Breakpoint بگذارید و داده‌ها را از SDK واکشی کنید.

+
+ +
+ ✅ چک‌لیست قبل از شروع: +
    +
  • Node.js نسخه ۲۰ یا بالاتر نصب است.
  • +
  • Firefox و افزونه Debugger for Firefox در VS Code نصب هستند.
  • +
  • فایل src/index.html هیچ تگ <script src="./js/SDK.min.js"> ندارد.
  • +
  • baseUri در manifest اصلی وجود ندارد و فقط در configs/dev.json تعریف شده است.
  • +
  • پورت ۳۰۰۰ آزاد است (در غیر این صورت آن را در webpack.config.js و dev.json هم‌زمان تغییر دهید).
  • +
  • آدرس https://localhost:3000/dist/index.html در مرورگر بدون خطا باز می‌شود.
  • +
+
+ +
+ 📚 منابع رسمی برای مطالعه بیشتر: +
    +
  • مخزن نمونه Hot Reload و Debug مایکروسافت: github.com/microsoft/azure-devops-extension-hot-reload-and-debug[reference:19]
  • +
  • مخزن نمونه رسمی SDK: github.com/microsoft/azure-devops-extension-sample
  • +
  • مستندات SDK: learn.microsoft.com/azure/devops/extend/develop/using-the-sdk
  • +
+
+
+
+ +
+ این مستند برای استفاده داخلی تیم توسعه تهیه شده است. تنظیمات امنیتی سازمان (مانند دسترسی به شبکه داخلی) باید پس از اتمام تست به حالت اولیه بازگردانده شود. +
+ +
+ + + +
+ + + \ No newline at end of file diff --git a/Documents/Docs/Developer/Azure Release Document v1.0.html b/Documents/Docs/Developer/Azure Release Document v1.0.html new file mode 100644 index 0000000..ecd03c8 --- /dev/null +++ b/Documents/Docs/Developer/Azure Release Document v1.0.html @@ -0,0 +1,1482 @@ + + + + + +راهنمای جامع بخش Release در Azure DevOps | مرجع عملیاتی مدیر انتشار + + + +
+
+
+
+ +
+
رایان پرداز کاوش
+
واحد مدیریت انتشار
+
+
+
+
شماره مستند: KB-1405-002
+
نسخه: ۱.۰
+
تاریخ تهیه: آبان ۱۴۰۵
+
طبقه‌بندی: داخلی
+
+
+
+RELEASE MANAGEMENT | AZURE DEVOPS +

راهنمای جامع بخش Release در Azure DevOps

+

امکانات، سناریوهای عملیاتی، REST API و ابزارهای مدیر انتشار

+
+
+
+
+همکاران گرامی،
+این مستند به‌عنوان مرجع عملیاتی کار با بخش Release در Azure DevOps و از منظر تحلیل مدیر انتشار تهیه شده است. محتوا منطبق بر سند «مستند فرآیند انتشار و استقرار نرم‌افزار نسخه ۲.۰.۰» سازمان (چرخه ۷ مرحله‌ای از ثبت درخواست توسط Tech Lead تا استقرار در محیط عملیاتی آبی، همراه با ۱۰ گیت تصمیم‌گیری) تدوین شده و مخاطبان آن تیم‌های DevOps، توسعه نرم‌افزار (.NET / React)، QA و تحلیل هستند. هدف، ایجاد زبان مشترک، استانداردسازی سناریوهای استقرار و فراهم‌کردن مسیر پایش و خودکارسازی کامل وضعیت انتشارها از طریق API است. +
+ +
+
+
۱
+
+

خلاصه اجرایی

+
Executive Summary
+
+
+
+

بخش Release در Azure DevOps (مسیر Pipelines ← Releases، معروف به Classic Release Pipeline) ارکستراتور استقرار چندمحیطی است: خروجی Build را به‌عنوان Artifact دریافت می‌کند، آن را از میان Stageهای متوالی یا موازی (Staging، UAT، Blue و…) عبور می‌دهد و در هر مرز، با Approval انسانی و Gate خودکار، تصمیم انتشار را کنترل‌پذیر و قابل‌ردیابی می‌کند. تقریباً هر آنچه در UI می‌بینید، از طریق REST API نیز قابل خواندن و کنترل است؛ همین ویژگی، Release را به ستون فقرات فرآیند انتشار v2.0.0 ما تبدیل می‌کند.

+
+
+
۷ مرحله
+
چرخه انتشار سازمان؛ از درخواست Tech Lead تا Blue
+
+
+
۱۰ گیت
+
تصمیم‌گیری کیفیت، قابل پیاده‌سازی با Approval و Gate
+
+
+
دید ۳۶۰°
+
پایش لحظه‌ای وضعیت ریلیزها از طریق REST API و رویدادها
+
+
+
+نتیجه کلیدی: با ترکیب «Stage + Approval + Gate» فرآیند ۱۰ گیته سازمان را عیناً روی Azure DevOps پیاده می‌کنیم و با ترکیب «REST API + Service Hooks» لایه پایش و گزارش‌دهی آن را به دستیار انتشار سازمان (xReleaseAssistant) متصل می‌سازیم؛ نتیجه، انتشار کنترل‌شده، شواهد حسابرسی کامل و حذف گزارش‌گیری دستی است. +
+
+
+
+
+
۲
+
+

مفاهیم و معماری Release

+
Core Concepts & Architecture
+
+
+
+

پیش از ورود به سناریوها، لازم است واژگان مشترک دقیقی داشته باشیم. جدول زیر اجزای سازنده یک Release Pipeline و کاربرد هرکدام را از نگاه مدیر انتشار خلاصه می‌کند:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
مفهومتعریفکاربرد برای مدیر انتشار
Release Definitionالگوی تکرارپذیر انتشار: Stageها، Artifactها، Triggerها، متغیرها و Approvalهامعادل «فرآیند انتشار» یک محصول؛ یک‌بار طراحی، بارها اجرا
Releaseیک اجرای مشخص از Definition با Artifactهای نسخه‌دار (Release-148 و…)واحد ردیابی انتشار؛ شناسه آن در گزارش‌ها و API محور همه‌چیز است
Artifactخروجی نسخه‌دار CI (Build، مخزن Git، NuGet و…) با Alias مشخصتضمین اینکه دقیقاً همان بسته تست‌شده منتشر می‌شود
Stage / Environmentمحیط منطقی استقرار (Staging، UAT، Blue) شامل Jobها و Taskهامرزهای تصمیم‌گیری؛ محل نصب Approval و Gate
Pre / Post-Deployment Approvalتأیید انسانی قبل یا بعد از استقرار هر Stage (فرد یا گروه، با Timeout)پیاده‌سازی گیت‌های انسانی G6، G7 و G9 فرآیند سازمان
Gateبررسی خودکار سلامت پیش از ورود به Stage (Monitor، REST، Work Item و…)پیاده‌سازی گیت‌های سیستمی G4 و G8 بدون دخالت انسان
Triggerشروع خودکار ریلیز: CD پس از بیلد، زمان‌بندی، یا Pull Requestحذف خطای «یادم رفت ریلیز بسازم» و کنترل پنجره انتشار
Variable Group / Key Vaultمتغیرهای مشترک با Scope سطح Release یا Stage؛ اتصال به Azure Key Vaultمدیریت متمرکز Connection Stringها و رازها بدون کپی دستی
Deployment Groupمجموعه سرورهای هدف با Agent نصب‌شده و برچسب (Tag)استقرار Rolling روی IaaS با کنترل درصد دسته‌ها
Task Groupبسته‌بندی چند Task به یک واحد قابل استفاده مجدداستانداردسازی «اسکریپت استقرار .NET» در همه Definitionها
Retention Policyسیاست نگهداری ریلیزها، لاگ‌ها و Artifactهاتطبیق با الزامات حسابرسی و مدیریت فضای ذخیره‌سازی
+
+💡 دو مسیر انتشار در Azure DevOps: مسیر Classic (همین بخش Releases) و مسیر مدرن YAML Multi-stage که در آن مفهوم Stage به environment و Approval/Gate به checks نگاشت می‌شود. تمرکز این مستند بر Classic است چون فرآیند فعلی سازمان روی آن اجرا می‌شود؛ در بخش ۱۲ برنامه مهاجرت تدریجی به YAML/Environments پیشنهاد شده است. +
+
+⚠ نکته راهبردی: سرمایه‌گذاری مایکروسافت روی YAML Pipelines و Environments متمرکز است و Classic Release در حالت نگهداری قرار دارد. بنابراین هر خودکارسازی جدید را «API-محور و مستقل از UI» طراحی می‌کنیم تا در مهاجرت آینده، فقط لایه اتصال تغییر کند نه کل فرآیند. +
+
+
+
+
+
۳
+
+

امکانات و قابلیت‌ها

+
Features & Capabilities
+
+
+
+

قابلیت‌های بخش Release را در چهار دسته کاربردی مرور می‌کنیم. این فهرست، مبنای انتخاب ابزار برای هر گیت و هر سناریو در ادامه مستند است:

+

الف) ارکستراسیون و استقرار:

+
    +
  • Stageهای متوالی و موازی: ترتیب دلخواه محیط‌ها با شرط اجرا (پس از Stage قبل، پس از کل Release، یا دستی)
  • +
  • چند Artifact در یک ریلیز: ترکیب بیلد Backend (.NET)، Frontend (React) و اسکریپت Database با نسخه‌های مستقل
  • +
  • Triggerها: CD پس از بیلد موفق، زمان‌بندی (Scheduled)، فیلتر Branch و مسیر، و Trigger مبتنی بر PR
  • +
  • Deployment Groups و Rolling Deploy: استقرار دسته‌ای روی سرورها با تعیین حداکثر درصد اهداف هم‌زمان
  • +
  • استقرار روی Slotهای App Service: پشتیبانی بومی Deploy to Slot و Swap برای الگوی Blue-Green
  • +
  • Redeploy و تلاش مجدد: اجرای دوباره همان ریلیز با همان Artifactها، یا Retry فقط Taskهای ناموفق
  • +
  • Draft Release و Manual Environments: آماده‌سازی پیش‌نویس ریلیز و انتخاب اینکه کدام Stageها دستی شروع شوند
  • +
  • Deployment Queue Settings: کنترل هم‌زمانی (صف ترتیبی، یا جدیدترین استقرار و لغو قبلی‌ها) برای جلوگیری از تداخل روی Blue
  • +
+

ب) کنترل کیفیت و تصمیم‌گیری:

+
    +
  • Approvalهای قبل/بعد: فرد یا گروه، ترتیب‌دار یا موازی، با Timeout و سیاست رد خودکار؛ درخواست‌کننده نمی‌تواند تأییدکننده خودش باشد
  • +
  • Gateهای خودکار: Query Azure Monitor Alerts، Invoke REST API، Invoke Azure Function، Query Work Items و Azure Policy Compliance — با فاصله نمونه‌برداری، تعداد موفقیت متوالی و Timeout قابل تنظیم
  • +
  • اعلان تأیید: ایمیل به Approverها + قابل اتصال به Teams از طریق Service Hooks
  • +
  • Clone Stage: کپی کامل تنظیمات یک Stage برای ساخت سریع محیط مشابه (مثلاً UAT از روی Staging)
  • +
+

ج) پیکربندی و امنیت:

+
    +
  • متغیرها با Scope: سطح Release یا Stage؛ مقدار Secret با قفل و masker در لاگ
  • +
  • Variable Group متصل به Key Vault: رازها فقط در زمان اجرا خوانده می‌شوند و در Definition ذخیره نمی‌شوند
  • +
  • مجوزهای Stage-سطحی: می‌توان اجازه تأیید/استقرار هر Stage را به تیم متفاوتی سپرد (QA برای Staging، مدیر انتشار برای Blue)
  • +
  • Artifact Filters: محدودکردن ریلیز به Branch یا Tag مشخص (مثلاً فقط release/*)
  • +
+

د) مشاهده‌پذیری و ردیابی:

+
    +
  • لاگ Task-سطحی: مشاهده آنلاین و دانلود ZIP کامل لاگ‌های هر ریلیز (از UI و API)
  • +
  • تاریخچه و مقایسه: Deployment History per Stage، مقایسه دو ریلیز، و فهرست Work Itemها/Commitهای بین دو ریلیز
  • +
  • داشبورد و اعلان: ویجت‌های Release، ایمیل‌های Subscription و رویدادهای Service Hook
  • +
  • Audit: ثبت اینکه چه کسی، چه زمانی، کدام Approval را تأیید/رد کرد
  • +
+
+✓ قابلیت طلایی برای Rollback: گزینه Redeploy دقیقاً همان Release قبلی را با همان Artifactهای نسخه‌دار دوباره اجرا می‌کند؛ یعنی بازگشت به نسخه قبل بدون بیلد مجدد و بدون ریسک «کد عوض‌شده». این قابلیت، ستون فقرات سناریوی Rollback در بخش ۴ است. +
+
+
+
+
+
۴
+
+

سناریوهای عملیاتی

+
Deployment Scenarios & Playbooks
+
+
+
+

در ادامه، هفت سناریوی پرتکرار سازمان را به‌صورت Playbook اجرایی مرور می‌کنیم. هر سناریو مشخص می‌کند کدام قابلیت Azure DevOps، کدام مرحله از چرخه ۷ مرحله‌ای را پوشش می‌دهد.

+

سناریو ۱ — Blue-Green برای Backend (.NET) با App Service Slots:

+
    +
  • گام ۱: Task از نوع AzureRmWebAppDeployment@4 با فعال‌بودن Deploy to Slot، بسته را روی Slot سبز (Green) مستقر می‌کند؛ ترافیک کاربران همچنان روی آبی (Blue) است
  • +
  • گام ۲: اجرای Smoke Test روی آدرس Slot سبز + Warm-up (Application Initialization)
  • +
  • گام ۳: Gate از نوع Azure Monitor بررسی می‌کند هیچ Alert فعالی روی Green وجود ندارد (گیت G8)
  • +
  • گام ۴: Pre-Deployment Approval مدیر انتشار روی Stage «Blue» (گیت G9)
  • +
  • گام ۵: Task از نوع AzureAppServiceManage@0 با Action «Swap Slots» نسخه جدید را به محیط عملیاتی آبی می‌برد
  • +
  • Rollback: در صورت بروز خطا، Swap مجدد؛ بازگشت ترافیک به نسخه قبل در چند ثانیه، بدون استقرار دوباره
  • +
+

سناریو ۲ — Canary / Rolling با Deployment Groups (سرورهای IaaS):

+
    +
  • سرورها را با Tagهایی مثل canary و wave-1 و wave-2 برچسب‌گذاری کنید
  • +
  • در Job از نوع Deployment Group، مقدار «Max number of targets in parallel» را روی ۲۵٪ بگذارید تا استقرار موج‌به‌موج پیش برود
  • +
  • پس از هر موج، اسکریپت Health Probe اجرا شود؛ شکست هر دسته، ادامه استقرار را متوقف می‌کند و فقط همان دسته آلوده است، نه کل ناوگان
  • +
+

سناریو ۳ — انتشار چندجزئی (Backend + Frontend + Database):

+
    +
  • سه Artifact با Aliasهای backend-drop، frontend-drop و db-migrations به یک Definition متصل شوند؛ نگاشت مستقیم با taxonomy زیرپروژه‌های سازمان (backend, frontend, service, database, mobile, infrastructure)
  • +
  • ترتیب Stageها: ابتدا Database (اجرای dotnet ef migrations bundle به‌صورت اسکریپت idempotent)، سپس Backend، سپس Frontend
  • +
  • Stage دیتابیس: Task پشتیبان‌گیری قبل از Migration + Approval جداگانه DBA + الگوی Expand/Contract برای تغییرات مخرب (حذف ستون هرگز در همان انتشار انجام نشود)
  • +
  • Frontend (React) روی Static Web App یا CDN با Versioned Path منتشر شود تا کش کاربران نسخه قدیمی را نبیند
  • +
+

سناریو ۴ — Hotfix با مسیر سریع (Fast-Track):

+
    +
  • Definition جداگانه «Shop-Hotfix» با Artifact Filter روی Branchهای hotfix/*
  • +
  • گیت‌های فشرده اما اجباری: تست واحد + Smoke + تأیید دونفره (Tech Lead و مدیر انتشار)؛ گیت UAT به‌صورت Post-Deployment پس از استقرار تکمیل می‌شود
  • +
  • ثبت اجباری Work Item نوع Bug و لینک آن در Description ریلیز؛ گزارش Hotfix در پایان هفته از API استخراج و به CAB ارسال می‌شود
  • +
+

سناریو ۵ — پنجره انتشار و ساعات مجاز:

+
    +
  • Schedule Trigger برای ساخت ریلیز در ساعت مقرر + Gate از نوع Invoke REST API که ساعت/روز مجاز را از سرویس تقویم سازمان استعلام می‌کند
  • +
  • Deployment Queue روی حالت ترتیبی تا دو ریلیز هم‌زمان به Blue نرسند (معادل Exclusive Lock در مسیر YAML)
  • +
  • در مسیر YAML، Check بومی «Business hours» و «Exclusive lock» همین کار را بدون کد انجام می‌دهند
  • +
+

سناریو ۶ — Feature Flag و انتشار تدریجی قابلیت:

+
    +
  • کد جدید خاموش (Dark) منتشر می‌شود؛ فعال‌سازی از Azure App Configuration با کتابخانه Feature Management در .NET و Endpoint پیکربندی برای React
  • +
  • فعال‌سازی موجی: ۵٪ کاربران ← ۲۵٪ ← ۱۰۰٪ با پایش متریک‌ها بین هر موج؛ Kill-Switch بدون هیچ استقرار مجددی
  • +
  • این سناریو «استقرار» را از «انتشار قابلیت» جدا می‌کند؛ ریسک گیت G9 به‌شدت کاهش می‌یابد
  • +
+

سناریو ۷ — Rollback خودکار:

+
    +
  • Auto-Redeploy Trigger را روی رویداد «شکست استقرار» تنظیم کنید تا آخرین ریلیز موفق دوباره اجرا شود
  • +
  • یا از طریق API: شناسه آخرین Artifact موفق را از Deployments API بگیرید و ریلیز جدید با همان instanceReference بسازید (نمونه در بخش ۶)
  • +
  • در الگوی Blue-Green، Rollback همان Swap مجدد است؛ سریع‌ترین گزینه و انتخاب پیش‌فرض ما برای Blue
  • +
+
+
+

Rolling / Canary

+
    +
  • زیرساخت لازم چند سرور + Deployment Group
  • +
  • سرعت Rollback متوسط (موج‌به‌موج)
  • +
  • هزینه زیرساخت بدون محیط مضاعف
  • +
  • مناسب برای سرویس‌های IaaS و ناوگان سرور
  • +
+
+ +
+
+⚠ قاعده غیرقابل‌مذاکره: هیچ Stage دیتابیس بدون Task پشتیبان‌گیری و Approval مسئول دیتابیس فعال نشود؛ و هیچ Migration مخربی (Drop/Rename) در همان انتشارِ تغییر کد اجرا نگردد. این قاعده در Definitionهای سازمان به‌صورت پیش‌فرض قالب‌سازی می‌شود. +
+
+
+
+
+
۵
+
+

انطباق فرآیند سازمان با Azure DevOps

+
Mapping Process v2.0.0 — 7 Stages & 10 Gates
+
+
+
+

بر اساس سند «فرآیند انتشار و استقرار نرم‌افزار نسخه ۲.۰.۰»، چرخه انتشار ما از ثبت درخواست توسط Tech Lead آغاز و به استقرار در محیط عملیاتی آبی ختم می‌شود. نقشه زیر، پیاده‌سازی پیشنهادی این چرخه ۷ مرحله‌ای بر بستر قابلیت‌های Azure DevOps است و باید در جلسه مشترک با DevOps با متن سند تطبیق نهایی شود:

+
+
+
+
۱. ثبت درخواست انتشار — Tech Lead
+

Work Item نوع «Release Request» در Azure Boards؛ شروع Release با reason=manual و Description حاوی شناسه درخواست و نسخه SemVer.

+
+
+
+
+
+
۲. بررسی آمادگی و دامنه — QA / Analysis
+

تکمیل Work Itemهای مرتبط و Release Notes؛ Gate از نوع Query Work Items برای اطمینان از نبود Bug با Severity بحرانیِ باز.

+
+
+
+
+
+
۳. آماده‌سازی Artifact — CI
+

بیلد موفق .NET و React با تست واحد و اسکن امنیت؛ Artifact Filter روی Branchهای release/* تا فقط بسته معتبر وارد چرخه شود.

+
+
+
+
+
+
۴. استقرار در Staging — خودکار
+

CD Trigger پس از بیلد؛ استقرار روی Slot سبز یا Deployment Group آزمایشگاهی؛ اجرای Migration با پشتیبان‌گیری.

+
+
+
+
+
+
۵. تأیید QA و UAT
+

اجرای رگرسیون + Smoke خودکار؛ Post-Deployment Approval گروه QA و سپس Approval گروه تحلیل برای UAT.

+
+
+
+
+
+
۶. گیت نهایی مدیر انتشار
+

Gateهای سیستمی (Azure Monitor بدون Alert + REST سلامت) و سپس Pre-Deployment Approval مدیر انتشار روی Stage «Blue».

+
+
+
+
+
+
۷. استقرار در محیط عملیاتی آبی (Blue)
+

Swap/Deploy نهایی + Gate سلامت پس از استقرار + اعلان Service Hook به Teams و xReleaseAssistant؛ ثبت شواهد در گزارش انطباق.

+
+
+
+
+

و اما ۱۰ گیت تصمیم‌گیری؛ جدول زیر نگاشت پیشنهادی هر گیت به مکانیزم اجرایی Azure DevOps و مالک آن است:

+ + + + + + + + + + + + + + + + + + + + + +
گیتعنوان کنترلیمکانیزم در Azure DevOpsمالک
G1کامل‌بودن درخواست و Release NotesQuery Work Items Gate + فیلدهای اجباری Work ItemAnalysis
G2مرور کد و انطباق BranchBranch Policy در Repos + Artifact FilterTech Lead
G3بیلد و تست واحد سبزپیش‌نیاز CI موفق برای Trigger ریلیزDevelopment
G4اسکن امنیت و وابستگی‌هاTask اسکن در CI + Gate استعلام نتیجه (REST)DevOps
G5استقرار موفق Stagingشرط Stage: اجرای پس از موفقیت Stage قبلخودکار
G6تأیید رگرسیون QAPost-Deployment Approval گروه QAQA
G7تأیید UAT / تحلیلApproval گروه Analysis روی Stage UATAnalysis
G8سلامت عملکردی محیطGate از نوع Query Azure Monitor Alertsخودکار
G9تأیید نهایی انتشارPre-Deployment Approval مدیر انتشار روی BlueRelease Manager
G10سلامت پس از استقرارPost-Deployment Gate + Smoke Test + Approval نهاییDevOps / RM
+
+ارزش انطباق: هر ۱۰ گیت در Azure DevOps دارای رکورد زمانی، تصمیم‌گیرنده و نتیجه است. خروجی Approvals API (بخش ۶) دقیقاً همان «شواهد گیت» است که گزارش انطباق v2.0.0 به آن نیاز دارد؛ یعنی حسابرسی از حالت دستی خارج و به خروجی سیستم تبدیل می‌شود. +
+
+
+
+
+
۶
+
+

REST API — دریافت وضعیت و کنترل ریلیزها

+
Release REST API v7.1 — Read, Monitor & Orchestrate
+
+
+
+

همه اطلاعات ریلیزها از REST API قابل دریافت است. نکته کلیدی: APIهای Classic Release روی زیردامنه اختصاصی vsrm.dev.azure.com ارائه می‌شوند (نه dev.azure.com معمولی) و نسخه پایدار فعلی api-version=7.1 است. الگوی پایه:

+
الگوی پایه فراخوانیBASE URL
+
https://vsrm.dev.azure.com/{organization}/{project}/_apis/release/{resource}?api-version=7.1
+

احراز هویت: ساده‌ترین روش، PAT با حداقل دسترسی است: برای پایش فقط Release → Read و برای کنترل، Read, write & execute. PAT در جایگاه «رمز عبور» با نام کاربری خالی، به‌صورت Basic ارسال می‌شود. برای اتوماسیون سازمانی، به‌جای PAT از توکن Entra ID (OAuth) استفاده کنید.

+
ساخت هدر احراز هویت و فهرست ریلیزهاcurl
+
# PAT در جایگاه رمز عبور، نام کاربری خالی (curl -u ":$PAT") +curl -s -u ":$AZDO_PAT" \ + "https://vsrm.dev.azure.com/rayanpardaz/Shop/_apis/release/releases?definitionId=7&$expand=environments&$top=20&api-version=7.1"
+

جدول Endpointهای کلیدی مدیر انتشار:

+ + + + + + + + + + + + + + + + + + + + + + + +
متدمسیر (نسبت به Base)کاربرد
GET/releasesفهرست ریلیزها با فیلتر definitionId، statusFilter، بازه زمانی و $expand=environments
GET/releases/{id}جزئیات کامل: Stageها، Taskها، Approvalها، متغیرها و Artifactها
POST/releasesایجاد ریلیز جدید (دستی/خودکار) با انتخاب نسخه Artifact
PATCH/releases/{id}تغییر وضعیت (abandoned)، نام، توضیح و keepForever
PATCH/releases/{id}/environments/{envId}شروع/تأیید ضمنی Stage، لغو، یا تلاش مجدد استقرار
GET/approvalsفهرست تأییدهای در انتظار (صندوق ورودی گیت‌های انسانی)
PATCH/approvals/{approvalId}تأیید / رد / واگذاری Approval با ثبت کامنت
GET/definitionsفهرست Definitionها (شناسه‌ها برای فیلترکردن)
GET/definitions/{id}ساختار کامل Stageها، Triggerها و Approvalها (مستندسازی خودکار فرآیند)
GET/deploymentsتاریخچه استقرارها با فیلتر وضعیت؛ منبع محاسبه سنجه‌های DORA
GET/releases/{id}/logsدانلود ZIP تمام لاگ‌های ریلیز (پیوست شواهد حسابرسی)
GET/releases/{id}/logs/{logId}متن لاگ یک Task مشخص
GET/releases/{id}/workitemsrefsWork Itemهای بین دو ریلیز (با baseReleaseId) — منبع تولید Release Notes
+

الف) دریافت وضعیت — نمونه پاسخ فهرست ریلیزها:

+
پاسخ ساده‌شده GET /releases?$expand=environmentsJSON
+
{ + "count": 1, + "value": [ + { + "id": 148, + "name": "Release-148", + "status": "active", + "createdOn": "2026-11-18T09:30:00Z", + "releaseDefinition": { "id": 7, "name": "Shop-Production" }, + "environments": [ + { "id": 412, "name": "Staging", "status": "succeeded", "rank": 1 }, + { "id": 413, "name": "Blue", "status": "inProgress", "rank": 2, + "preDeployApprovals": [ + { "id": 901, "status": "pending", + "approver": { "displayName": "هادی خزاعی اصل" } } + ] + } + ] + } + ] +}
+

ب) ایجاد ریلیز جدید با نسخه Artifact مشخص:

+
بدنه POST /releases — شروع کنترل‌شده چرخه از روی درخواستJSON
+
{ + "definitionId": 7, + "description": "انتشار نسخه 1.2.0 — درخواست RR-2311 (Tech Lead)", + "isDraft": false, + "reason": "manual", + "artifacts": [ + { "alias": "backend-drop", + "instanceReference": { "id": "4521", "name": "2026.11.18.3" } } + ], + "variables": { + "Release.Version": { "value": "1.2.0" } + } +}
+

ج) تأیید یا رد گیت انسانی (Approval):

+
صندوق تأییدهای در انتظار و سپس تصمیم‌گیری روی Approval 901HTTP
+
# ۱) همه تأییدهای در انتظار من و گروه‌هایم +GET /_apis/release/approvals?statusFilter=pending&includeMyGroupApprovals=true&$top=50&api-version=7.1 + +# ۲) تأیید گیت G9 با ثبت شاهد +PATCH /_apis/release/approvals/901?api-version=7.1 +{ "status": "approved", "comments": "گیت‌های G1 تا G8 پاس شد — تأیید نهایی انتشار" } + +# رد: "status": "rejected" | واگذاری: "status": "reassigned" + assignedTo + +# معادل جایگزین: شروع/لغو مستقیم Stage +PATCH /_apis/release/releases/148/environments/413?api-version=7.1 +{ "status": "inProgress", "comment": "شروع استقرار Blue" } # یا "canceled" / "queued" برای Retry
+

د) رهاکردن ریلیز و تاریخچه استقرارها:

+
لغو ریلیز معیوب + استخراج تاریخچه برای Rollback و DORAHTTP
+
# رهاکردن ریلیز (Abandon) با دلیل +PATCH /_apis/release/releases/148?api-version=7.1 +{ "status": "abandoned", "comment": "لغو به‌دلیل Bug بحرانی #2311" } + +# آخرین استقرارهای Stage آبی (definitionEnvironmentId از GET definitions/{id}) +GET /_apis/release/deployments?definitionId=7&definitionEnvironmentId=23&latestAttemptsOnly=true&$top=50&api-version=7.1 + +# فقط استقرارهای ناموفق برای محاسبه Change Failure Rate +GET /_apis/release/deployments?definitionId=7&deploymentStatus=failed&api-version=7.1
+

ه) جدول وضعیت‌ها (Enum) — واژگان پایش:

+ + + + + + + + + + + + + + + + +
فیلدمقادیر ممکنتفسیر عملیاتی
release.statusactive، abandoned (+ isDraft=true)ریلیز جاری، رهاشده، یا پیش‌نویس
environment.statusnotStarted، queued، inProgress، succeeded، partiallySucceeded، failed، canceled، rejected، skippedوضعیت هر Stage؛ مبنای رنگ‌بندی داشبورد
approval.statuspending، approved، rejected، reassigned، canceled، skippedوضعیت گیت انسانی؛ pending یعنی گلوگاه تصمیم
approval.approvalTypepreDeploy، postDeployگیت قبل از استقرار یا بعد از آن
release.reasonmanual، continuousIntegration، scheduleمنشأ ایجاد ریلیز برای گزارش تفکیکی
deployment.operationStatusqueued، scheduled، pending، approved، rejected، inProgress، completed و…وضعیت عملیات هر تلاش استقرار
+

و) نمونه‌کدهای آماده بهره‌برداری:

+
گزارش سریع وضعیت — مناسب اجرای روزانه در Pipeline مانیتورینگPowerShell
+
$auth = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$env:AZDO_PAT")) +$uri = "https://vsrm.dev.azure.com/rayanpardaz/Shop/_apis/release/releases?definitionId=7&`$expand=environments&`$top=10&api-version=7.1" + +(Invoke-RestMethod -Uri $uri -Headers @{ Authorization = "Basic $auth" }).value | + ForEach-Object { + [pscustomobject]@{ + Release = $_.name + Status = $_.status + Stages = ($_.environments | ForEach-Object { "$($_.name)=$($_.status)" }) -join ' | ' + } + } | Format-Table -AutoSize
+
کلاینت پایش در بک‌اند سازمانی — پایه اتصال xReleaseAssistantC# / .NET
+
using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; + +using var http = new HttpClient { + BaseAddress = new Uri("https://vsrm.dev.azure.com/rayanpardaz/Shop/") +}; +var token = Convert.ToBase64String(Encoding.ASCII.GetBytes($":{pat}")); +http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", token); + +var json = await http.GetStringAsync( + "_apis/release/releases?definitionId=7&$expand=environments&$top=20&api-version=7.1"); + +using var doc = JsonDocument.Parse(json); +foreach (var rel in doc.RootElement.GetProperty("value").EnumerateArray()) +{ + Console.WriteLine($"{rel.GetProperty("name")} — {rel.GetProperty("status")}"); + foreach (var env in rel.GetProperty("environments").EnumerateArray()) + Console.WriteLine($" {env.GetProperty("name")}: {env.GetProperty("status")}"); +}
+
اسکریپت پایش سبک — مناسب نمونه‌سازی سریع و گزارش‌گیریPython
+
import os, requests + +BASE = "https://vsrm.dev.azure.com/rayanpardaz/Shop/_apis/release" +s = requests.Session() +s.auth = ("", os.environ["AZDO_PAT"]) # PAT در جایگاه رمز عبور + +params = {"definitionId": 7, "$expand": "environments", + "$top": 20, "api-version": "7.1"} +releases = s.get(f"{BASE}/releases", params=params, timeout=30).json()["value"] + +for rel in releases: + stages = " | ".join(f'{e["name"]}={e["status"]}' + for e in rel.get("environments", [])) + print(f'{rel["name"]} [{rel["status"]}] → {stages}')
+
+⚠ نکات عملیاتی API: +
    +
  • صفحه‌بندی با continuationToken انجام می‌شود؛ برای فهرست‌های بزرگ حلقه بزنید و به count اکتفا نکنید
  • +
  • محدودیت نرخ (TSTU) وجود دارد؛ پاسخ 429 را با هدر Retry-After و Backoff نمایی مدیریت کنید
  • +
  • Polling را حداکثر هر ۳۰–۶۰ ثانیه انجام دهید؛ برای واکنش لحظه‌ای، Service Hooks (بخش ۷) انتخاب صحیح است
  • +
  • فیلترهای minCreatedTime / maxCreatedTime حجم پاسخ را برای گزارش‌های بازه‌ای به‌شدت کم می‌کنند
  • +
  • در مسیر YAML، معادل‌ها متفاوت‌اند: محیط‌ها از _apis/distributedtask/environments و تأییدها از _apis/pipelines/approvals (نسخه preview) خوانده می‌شوند
  • +
+
+
+
+
+
+
۷
+
+

رویدادها، اعلان‌ها و Service Hooks

+
Event-Driven Integration
+
+
+
+

به‌جای پرس‌وجوی مداوم، Azure DevOps می‌تواند رویدادهای Release را به‌صورت Push به هر Webhook (از جمله xReleaseAssistant و Teams) ارسال کند. مسیر تعریف: Project Settings ← Service hooks ← ساخت Subscription با Publisher «Release». رویدادهای کلیدی:

+ + + + + + + + + + + + + + + + + + +
رویدادزمان وقوعکاربرد برای مدیر انتشار
release-created-eventایجاد ریلیز جدیدثبت شروع چرخه و اطلاع‌رسانی به کانال انتشار
deployment-started-eventشروع استقرار یک Stageبه‌روزرسانی زنده داشبورد وضعیت
deployment-completed-eventپایان استقرار (موفق/ناموفق)ثبت نتیجه، محاسبه سنجه‌ها، تریگر گزارش
deployment-approval-pending-eventتشکیل گیت انسانی در انتظاریادآوری به Approver و پایش SLA تصمیم‌گیری
deployment-approval-completed-eventتکمیل چرخه تأییدثبت شاهد گیت در گزارش انطباق
release-deployment-approved-eventتأیید یک Approvalردیابی اینکه چه کسی کدام گیت را پاس کرد
release-deployment-rejected-eventرد یک Approvalهشدار فوری + ثبت دلیل رد
release-abandoned-eventرهاشدن ریلیزثبت در گزارش هفتگی لغوها و تحلیل علت
+
نمونه ساده‌شده Payload رویداد پایان استقرار — ورودی Webhook دستیارJSON
+
{ + "eventType": "ms.vss-release.deployment-completed-event", + "createdDate": "2026-11-18T10:05:12Z", + "resource": { + "environment": { + "releaseId": 148, + "releaseName": "Release-148", + "definitionName": "Shop-Production", + "name": "Blue", + "status": "succeeded" + }, + "comment": "استقرار با موفقیت پایان یافت" + } +}
+
+
+

Polling با REST API

+
    +
  • تأخیر داده به اندازه بازه Polling
  • +
  • مصرف سهمیه TSTU مستمر
  • +
  • پیچیدگی پیاده‌سازی کم
  • +
  • مناسب برای گزارش‌های دوره‌ای و Snapshot
  • +
+
+ +
+
+💡 معماری پیشنهادی: Service Hooks برای «واکنش لحظه‌ای» + یک Snapshot شبانه با REST API برای «تطبیق و ترمیم داده» (اگر رویدادی گم شد). این ترکیب، هم سرعت دارد هم صحت داده را تضمین می‌کند و دقیقاً همان الگویی است که برای xReleaseAssistant پیشنهاد می‌کنم. +
+
+
+
+
+
۸
+
+

پایش، داشبورد و سنجه‌های DORA

+
Monitoring, Dashboards & Delivery Metrics
+
+
+
+

مدیر انتشار بدون سنجه، فقط اپراتور استقرار است. چهار سنجه استاندارد DORA را می‌توان مستقیماً از داده‌های Release استخراج کرد:

+
+
+
Frequency
+
تعداد استقرار موفق در بازه زمانی
+
+
+
Lead Time
+
فاصله Commit تا استقرار در Blue
+
+
+
CFR + MTTR
+
نرخ خرابی تغییر و زمان بازیابی سرویس
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
سنجهفرمول محاسبهمنبع داده در Azure DevOps
Deployment Frequencyتعداد استقرار موفق روی Blue در هفته/ماهGET /deployments با فیلتر Stage آبی و وضعیت succeeded
Lead Time for Changesزمان اولین Commit نسخه تا completedTime استقرار Blueزمان Commit از Build/Artifact + زمان استقرار از Deployments API
Change Failure Rateاستقرارهای منجر به خرابی ÷ کل استقرارهای BluedeploymentStatus=failed + ریلیزهای Hotfix/Rollback (از reason و description)
Failed Deployment Recovery Timeفاصله استقرار ناموفق تا استقرار موفق بعدی روی Blueمقایسه زمانی دو رکورد متوالی در Deployments API
+

ابزارهای پایش روزمره:

+
    +
  • ویجت‌های Dashboard: ویجت‌های Release (نمای Definition و وضعیت استقرار) روی داشبورد تیمی؛ اولین صفحه‌ای که هر صبح باز می‌کنیم
  • +
  • Application Insights: Availability Test پس از هر استقرار + متریک‌های Latency/Error Rate؛ همین‌ها خوراک Gate «Azure Monitor» هستند
  • +
  • Azure Monitor Alerts: تعریف Alert روی Error Rate بالای آستانه؛ Gate به‌صورت خودکار ورود به Blue را مسدود می‌کند
  • +
  • خروجی تحلیلی: برای Classic Release از REST API به انبار داده/Power BI؛ برای YAML از نماهای Analytics و OData
  • +
  • گزارش هفتگی خودکار: Digest وضعیت (موفق/ناموفق/لغوشده، میانگین زمان انتظار Approvalها، Top گلوگاه‌ها) در Teams — با xReleaseAssistant
  • +
+
+✓ سنجه پنهان اما حیاتی: «میانگین زمان انتظار Approval» را از فاصله createdOn تا تصمیم در Approvals API محاسبه کنید. تجربه نشان می‌دهد بزرگ‌ترین گلوگاه Lead Time در سازمان‌ها، استقرار نیست؛ انتظار برای تصمیم انسانی است. این سنجه را در گزارش هفتگی CAB بگنجانید. +
+
+
+
+
+
۹
+
+

امنیت، دسترسی‌ها و حسابرسی

+
Security, Permissions & Audit
+
+
+
+

Release آخرین خط دفاعی محصول است؛ دسترسی‌های آن باید حداقلی، تفکیک‌شده و قابل‌حسابرسی باشد:

+

الف) مدل دسترسی:

+
    +
  • سه سطح مجوز: پروژه، Definition و Stage؛ یعنی می‌توان به QA فقط حق تأیید Stage آزمایشگاهی داد، بدون هیچ دسترسی به Blue
  • +
  • تفکیک وظایف (SoD): درخواست‌کننده استقرار نمی‌تواند تأییدکننده خودش باشد؛ این قاعده را در تنظیمات Approval فعال نگه دارید
  • +
  • گروه‌محوری: Approvalها را به Group بدهید نه Person؛ با جابه‌جایی نیروها فرآیند نمی‌شکند
  • +
  • Service Connectionها: اتصال به Azure با Workload Identity Federation (بدون Secret ماندگار) و Scope محدود به Resource Group هدف
  • +
+

ب) مدیریت رازها و توکن‌ها:

+
    +
  • Key Vault: همه رازهای استقرار در Variable Group متصل به Key Vault؛ هیچ Connection String plaintext در Definition نباشد
  • +
  • PAT حداقلی: برای پایش فقط Release (Read)؛ عمر حداکثر ۹۰ روز با چرخش زمان‌بندی‌شده و ثبت در فهرست توکن‌های سازمان
  • +
  • Secret Masking: متغیرهای Secret در لاگ‌ها Mask می‌شوند؛ هرگز آن‌ها را به متغیر معمولی تبدیل نکنید
  • +
+

ج) حسابرسی و شواهد:

+
    +
  • Auditing سازمانی: رویدادهای تغییر مجوز، حذف ریلیز و تغییر Definition در بخش Auditing ثبت می‌شود؛ Stream به Azure Monitor Logs/Sentinel برای نگهداری بلندمدت
  • +
  • Retention Policy: بازه نگهداری ریلیزها و لاگ‌ها را با الزامات حسابرسی هم‌تراز کنید؛ ریلیزهای Milestone را با keepForever نگه دارید
  • +
  • یکپارچگی Artifact: Artifact Filter روی Branchهای محافظت‌شده + Branch Policy (مرور اجباری و CI سبز) تا بسته دست‌کاری‌شده وارد چرخه نشود
  • +
+
+⚠ ضدالگو: استفاده از PAT شخصی یک نفر برای همه اتوماسیون‌های سازمانی. با خروج آن فرد، کل پایش و یکپارچه‌سازی می‌شکند. برای سرویس‌ها از Service Principal / Managed Identity با توکن OAuth استفاده کنید و PAT را فقط به ابزارهای موقت و شخصی محدود نگه دارید. +
+
+
+
+
+
۱۰
+
+

یکپارچه‌سازی با xReleaseAssistant

+
Integration Blueprint — v1.1.0 → v1.2.0
+
+
+
+

دستیار انتشار سازمان (xReleaseAssistant نسخه ۱.۱.۰) در حال حاضر حلقه اتصال تیم‌هاست. پیشنهاد من برای نسخه بعدی، افزودن «لایه اتصال Azure DevOps» با قابلیت‌های زیر است که همگی بر APIهای معرفی‌شده در این مستند تکیه دارند:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
نیاز مدیر انتشارقابلیت پیشنهادی در دستیارAPI / مکانیزم پشتوانه
داشبورد زنده وضعیتدریافت رویدادها و به‌روزرسانی لحظه‌ای وضعیت هر ریلیز/StageService Hooks (بخش ۷)
گزارش دوره‌ای استانداردSnapshot شبانه و تولید گزارش HTML بر اساس قالب مصوب سازمانGET /releases + GET /deployments
Release Notes خودکاراستخراج Work Itemها و Commitهای بین دو ریلیز و درج در گزارشGET /releases/{id}/workitemsrefs
شواهد ۱۰ گیتپیوست خودکار «چه کسی، چه زمانی، چه تصمیمی» به گزارش انطباق v2.0.0GET /approvals + Audit
هشدار SLA گیت‌هایادآوری Approvalهای pending بیش از آستانه (مثلاً ۴ ساعت) در Teamsapproval-pending hook + GET /approvals?statusFilter=pending
گزارش تفکیکی زیرپروژه‌هافیلتر گزارش بر اساس type زیرپروژه در سه سطح metadataنگاشت ساختار داده‌ای سازمان به Definition/Artifact/Stage
+

نکته طراحی: ساختار داده‌ای دستیار باید همان الگوی مصوب سازمان را حفظ کند — فیلد metadata در سه سطح Root، Project و Sub-project، و فیلد type زیرپروژه‌ها فقط از مجموعه مجاز {backend, frontend, service, database, mobile, infrastructure}. نگاشت پیشنهادی: هر Release Definition به یک Project، هر Artifact به یک Sub-project (با type متناظر) و هر Stage به یک محیط استقرار نگاشت شود تا گزارش‌ها بدون تغییر ساختار، فیلترپذیر بمانند.

+
+✓ خروجی ملموس نسخه ۱.۲.۰: «صبحانه انتشار» — هر روز ساعت ۸، یک گزارش یک‌صفحه‌ای در Teams شامل ریلیزهای فعال، گیت‌های در انتظار با نام تصمیم‌گیرنده، استقرارهای ناموفق دیشب و روند هفتگی DORA. صفر کلیک، صفر گزارش‌گیری دستی. +
+
+
+
+
+
۱۱
+
+

منابع و مستندات رسمی

+
Official References — Microsoft Learn
+
+
+
+

مبنای فنی این مستند، مستندات رسمی مایکروسافت است. نقل‌قول‌های زیر خلاصه مضمون (نه عین عبارت) آن مستندات هستند:

+
+

تأییدها و بررسی‌ها (Approvals & Checks) مالکِ محیط، یعنی Environment، هستند نه Pipeline؛ به این ترتیب هر خط لوله‌ای که بخواهد به آن محیط مستقر شود، به‌صورت خودکار مشمول همان کنترل‌ها می‌شود.

+
— Microsoft Learn, Define approvals and checks (خلاصه مضمون)
+
+
+

گیت‌های Release پیش از ورود به Stage، سیگنال‌های سلامت را از سرویس‌های بیرونی (مانند Azure Monitor یا REST API) به‌صورت دوره‌ای نمونه‌برداری می‌کنند و تا رسیدن به وضعیت سالمِ پایدار، استقرار را به تعویق می‌اندازند.

+
— Microsoft Learn, Control deployments using gates (خلاصه مضمون)
+
+
+

Deployment Group مجموعه‌ای از ماشین‌های هدف با Agent است که استقرار تدریجی (Rolling) روی گروه‌های برچسب‌خورده سرور را با کنترل تعداد اهداف هم‌زمان ممکن می‌کند.

+
— Microsoft Learn, Deployment groups (خلاصه مضمون)
+
+

فهرست کامل منابع:

+
    +
  • +Release Pipelines — Concepts & How-to +مرجع کامل مفاهیم Classic Release، Stageها، Triggerها و Artifactها +
    منبع: https://learn.microsoft.com/azure/devops/pipelines/release/
    +
  • +
  • +Releases — REST API 7.1 +List / Get / Create / Update ریلیزها و لاگ‌ها +
    منبع: https://learn.microsoft.com/rest/api/azure/devops/release/releases
    +
  • +
  • +Approvals — REST API 7.1 +فهرست و تصمیم‌گیری روی تأییدهای انسانی +
    منبع: https://learn.microsoft.com/rest/api/azure/devops/release/approvals
    +
  • +
  • +Definitions & Deployments — REST API 7.1 +ساختار Definitionها و تاریخچه استقرارها +
    منبع: https://learn.microsoft.com/rest/api/azure/devops/release/definitions
    +
  • +
  • +Approvals and Checks (YAML Environments) +کنترل‌های مسیر مدرن: Business hours، Exclusive lock، Required template +
    منبع: https://learn.microsoft.com/azure/devops/pipelines/process/approvals
    +
  • +
  • +Deployment Groups +استقرار Rolling روی سرورهای IaaS +
    منبع: https://learn.microsoft.com/azure/devops/pipelines/release/deployment-groups/
    +
  • +
  • +Service Hooks — Event Reference +فهرست رویدادهای Release و ساختار Payload +
    منبع: https://learn.microsoft.com/azure/devops/service-hooks/events
    +
  • +
  • +Permissions & Auditing +مدل مجوزها و حسابرسی سازمانی +
    منبع: https://learn.microsoft.com/azure/devops/organizations/security/
    +
  • +
+
+
+
+
+
۱۲
+
+

جمع‌بندی، نقشه راه و پیشنهاد

+
Final Summary, Roadmap & Recommendation
+
+
+
+

بخش Release در Azure DevOps تمام اجزای لازم برای اجرای دقیق فرآیند v2.0.0 سازمان را در اختیار دارد. جمع‌بندی ارزش‌ها از نگاه مدیر انتشار:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
قابلیت کلیدیارزش برای مدیر انتشارابزار اجرایی
Stage + Approval + Gateپیاده‌سازی عین‌به‌عین ۱۰ گیت با شاهد سیستمیPre/Post Approval، Gateهای Monitor/REST/Work Item
Blue-Green با SlotsRollback ثانیه‌ای و تست کامل پیش از ترافیکDeploy to Slot + Swap + Approval
REST API v7.1پایش و کنترل کامل بدون وابستگی به UIvsrm.dev.azure.com + PAT حداقلی / OAuth
Service Hooksواکنش لحظه‌ای و حذف گزارش‌گیری دستیWebhook به Teams و xReleaseAssistant
Deployments APIسنجه‌های DORA با داده واقعی، نه برآوردتاریخچه استقرار + محاسبه دوره‌ای
Audit + Retentionآمادگی دائمی برای حسابرسی و CABAuditing، keepForever، گزارش انطباق خودکار
+

نقشه راه پیشنهادی اجرا:

+ + + + + + + + + + + + + + + + + + + + + + + + + +
فازبازهاقدامات
۱. برد سریع۲ هفتهPAT فقط‌خواندنی پایش + Service Hooks به Teams + ویجت داشبورد + گزارش Snapshot شبانه
۲. استانداردسازی۱–۲ ماهقالب Definition مرجع با ۱۰ گیت، گروه‌های Approval، Key Vault، سناریوی Blue-Green و Hotfix + محاسبه DORA
۳. بلوغ و آینده۳–۶ ماهxReleaseAssistant v1.2.0 (شواهد گیت + Release Notes خودکار) + ارزیابی مهاجرت تدریجی به YAML/Environments با حفظ لایه API
+
+

🎯 پیشنهاد نهایی

+

فرآیند ۷ مرحله‌ای و ۱۰ گیته سازمان را روی همان بخش Classic Release فعلی، به‌صورت قالب استاندارد Definition پیاده کنیم و هم‌زمان لایه پایش API-محور را بسازیم؛ زیرا این لایه در مهاجرت آینده به YAML نیز سرمایه ماندگار ما خواهد بود.

+

اولویت اول من به‌عنوان مدیر انتشار: حذف گلوگاه تصمیم‌گیری با پایش SLA گیت‌های انسانی، و حذف گزارش‌گیری دستی با اتصال رویدادها به دستیار انتشار.

+
+💎 ارزش پیشنهادی:
+انتشار کنترل‌شده با ۱۰ گیت سیستمی + Rollback ثانیه‌ای در Blue + دید ۳۶۰° از API + گزارش انطباق خودکار +
+
+
+📞 گام بعدی: پیشنهاد می‌کنم جلسه‌ای مشترک با DevOps برای (۱) صدور PAT مانیتورینگ با دسترسی Release (Read)، (۲) تعریف Subscriptionهای Service Hook و (۳) تطبیق نهایی نقشه ۱۰ گیت با متن سند v2.0.0 برگزار شود. خروجی جلسه، Backlog نسخه ۱.۲.۰ دستیار انتشار خواهد بود. +
+
+
+
+این مستند داخلی بوده و صرفاً جهت استفاده تیم‌های فنی رایان پرداز کاوش تهیه شده است. نمونه‌کدها و نام‌های نمونه (rayanpardaz/Shop) باید با مقادیر واقعی سازمان جایگزین شوند. هرگونه افشا خارج از سازمان بدون اجازه کتبی ممنوع است. +
+
+ +
+ + \ No newline at end of file diff --git a/Documents/Resources/ZeroMQ/Includes/Mql/Lang/Error.mqh b/Documents/Resources/ZeroMQ/Includes/Mql/Lang/Error.mqh new file mode 100644 index 0000000..d1a8571 Binary files /dev/null and b/Documents/Resources/ZeroMQ/Includes/Mql/Lang/Error.mqh differ diff --git a/Documents/Resources/ZeroMQ/Includes/Mql/Lang/GlobalVariable.mqh b/Documents/Resources/ZeroMQ/Includes/Mql/Lang/GlobalVariable.mqh new file mode 100644 index 0000000..f662661 --- /dev/null +++ b/Documents/Resources/ZeroMQ/Includes/Mql/Lang/GlobalVariable.mqh @@ -0,0 +1,349 @@ +//+------------------------------------------------------------------+ +//| Module: Lang/GlobalVariable.mqh | +//| This file is part of the mql4-lib project: | +//| https://github.com/dingmaotu/mql4-lib | +//| | +//| Copyright 2017 Li Ding | +//| | +//| Licensed under the Apache License, Version 2.0 (the "License"); | +//| you may not use this file except in compliance with the License. | +//| You may obtain a copy of the License at | +//| | +//| http://www.apache.org/licenses/LICENSE-2.0 | +//| | +//| Unless required by applicable law or agreed to in writing, | +//| software distributed under the License is distributed on an | +//| "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, | +//| either express or implied. | +//| See the License for the specific language governing permissions | +//| and limitations under the License. | +//+------------------------------------------------------------------+ +#property strict +//+------------------------------------------------------------------+ +//| Encapsulates global variable functions | +//+------------------------------------------------------------------+ +class GlobalVariable +{ +public: + static int total() + { + return GlobalVariablesTotal(); + } + static string name(int index) + { + return GlobalVariableName(index); + } + static void flush() + { + GlobalVariablesFlush(); + } + + static bool exists(string name) + { + return GlobalVariableCheck(name); + } + static datetime lastAccess(string name) + { + return GlobalVariableTime(name); + } + + static bool makeTemp(string name) + { + return GlobalVariableTemp(name); + } + static double get(string name) + { + return GlobalVariableGet(name); + } + static bool get(string name, double &value) + { + return (bool)GlobalVariableGet(name, value); + } + static bool set(string name, double value) + { + return (bool)GlobalVariableSet(name, value); + } + static bool setOn(string name, double value, double check) + { + return GlobalVariableSetOnCondition(name, value, check); + } + + static bool remove(string name) + { + return (bool)GlobalVariableDel(name); + } + static bool removeAll(string prefix = NULL, datetime before = 0) + { + return (bool)GlobalVariablesDeleteAll(prefix, before); + } +}; +//+------------------------------------------------------------------+ +//| TempVar is a variable whose life time is the same as the program | +//+------------------------------------------------------------------+ +class TempVar +{ +private: + string m_name; + bool m_owned; + +public: + TempVar(string name, bool create = false) : m_name(name), m_owned(create) + { + if (create) + { + GlobalVariable::makeTemp(name); + } + } + ~TempVar() + { + if (m_owned && isValid()) + { + GlobalVariable::remove(m_name); + } + } + + bool isValid() const + { + return GlobalVariable::exists(m_name); + } + string getName() const + { + return m_name; + } + bool set(double value) + { + return GlobalVariable::set(m_name, value); + } + double get() const + { + return GlobalVariable::get(m_name); + } + bool setOn(double value, double check) + { + return GlobalVariable::setOn(m_name, value, check); + } + datetime lastAccess() const + { + return GlobalVariable::lastAccess(m_name); + } +}; +//+------------------------------------------------------------------+ +//| | +//+------------------------------------------------------------------+ +class AtomicVar : public TempVar +{ +public: + AtomicVar(string name, long initial, bool create = false) : TempVar(name, create) + { + set(initial); + } + long increment(long by = 1); + long decrement(long by = 1) + { + return increment(-by); + } +}; +//+------------------------------------------------------------------+ +//| | +//+------------------------------------------------------------------+ +long AtomicVar::increment(long by) +{ + bool success = false; + long value; + do + { + value = (long)get(); + success = setOn(value + by, value); + } while (!success && !IsStopped()); + return (value + by); +} +//+------------------------------------------------------------------+ +//| | +//+------------------------------------------------------------------+ +class Semaphore +{ +private: + TempVar m_var; + +public: + Semaphore(string name, long initial = 0); + bool isValid() const + { + return m_var.isValid(); + } + bool acquire(); + void release(); +}; +//+------------------------------------------------------------------+ +//| | +//+------------------------------------------------------------------+ +Semaphore::Semaphore(string name, long initial) + : m_var(name, initial != 0) +{ + if (initial != 0) + { + m_var.set(initial); + } +} +//+------------------------------------------------------------------+ +//| | +//+------------------------------------------------------------------+ +bool Semaphore::acquire(void) +{ + bool success = false; + do + { + long value = (long)m_var.get(); + if (value == 0) + return false; + success = m_var.setOn(value - 1, value); + } while (!success && !IsStopped()); + return success; +} +//+------------------------------------------------------------------+ +//| | +//+------------------------------------------------------------------+ +void Semaphore::release(void) +{ + bool success = false; + do + { + long value = (long)m_var.get(); + success = m_var.setOn(value + 1, value); + } while (!success && !IsStopped()); +} +//+------------------------------------------------------------------+ +//| CriticalSection object for making atomic operations | +//| | +//| An exmaple of creating a global context (the creation and destroy| +//| are both enclosed between the SAME critical section): | +//| | +//| enter() | +//| if(refcount==0) create context | +//| else refcontext | +//| increase refcount | +//| leave() | +//| | +//| enter() | +//| decrease refcount | +//| if(refcount==0) context destroy | +//| leave() | +//+------------------------------------------------------------------+ +class CriticalSection +{ +private: + const string m_name; + +public: + CriticalSection(string name) : m_name(name) {} + + bool isValid() const + { + return m_name != NULL; + } + string getName() const + { + return m_name; + } + + void enter() + { + GlobalVariable::remove(m_name); + while (!GlobalVariable::makeTemp(m_name) && !IsStopped()) + Sleep(100); + } + bool tryEnter() + { + return GlobalVariable::makeTemp(m_name); + } + void leave() + { + GlobalVariable::remove(m_name); + } +}; +//+------------------------------------------------------------------+ +//| HandleManager should implement 2 methods: create & destroy | +//+------------------------------------------------------------------+ +template +interface HandleManager +{ + T create(); + void destroy(T); +}; +//+------------------------------------------------------------------+ +//| A reference counted global pointer (or handle) | +//| Generic type parameter T can be long or int depending the handle | +//| length (64bit or 32bit) | +//+------------------------------------------------------------------+ +template +class GlobalHandle +{ +private: + CriticalSection m_cs; + string m_refName; + string m_counterName; + +protected: + T m_ref; + HandleManager *m_hm; + +public: + GlobalHandle(string sharedKey = NULL) : m_cs(sharedKey) + { + m_refName = m_cs.getName() + "_Ref"; + m_counterName = m_cs.getName() + "_Count"; + m_hm = new HM; + if (!m_cs.isValid()) + m_ref = m_hm.create(); + else + { + m_cs.enter(); + if (!GlobalVariable::exists(m_counterName)) + { + GlobalVariable::makeTemp(m_counterName); + GlobalVariable::set(m_counterName, 0); + } + if (long(GlobalVariable::get(m_counterName)) == 0) + { + m_ref = m_hm.create(); + if (!GlobalVariable::exists(m_refName)) + { + GlobalVariable::makeTemp(m_refName); + GlobalVariable::set(m_refName, m_ref); + } + } + else + { + m_ref = (T)(GlobalVariable::get(m_refName)); + } + GlobalVariable::set(m_counterName, GlobalVariable::get(m_counterName) + 1); + m_cs.leave(); + } + } + ~GlobalHandle() + { + if (!m_cs.isValid()) + { + m_hm.destroy(m_ref); + } + else + { + m_cs.enter(); + GlobalVariable::set(m_counterName, GlobalVariable::get(m_counterName) - 1); + if (long(GlobalVariable::get(m_counterName)) == 0) + { + m_hm.destroy(m_ref); + GlobalVariable::remove(m_refName); + GlobalVariable::remove(m_counterName); + } + m_cs.leave(); + } + delete m_hm; + } + + T ref() const + { + return m_ref; + } +}; +//+------------------------------------------------------------------+ diff --git a/Documents/Resources/ZeroMQ/Includes/Mql/Lang/Mql.mqh b/Documents/Resources/ZeroMQ/Includes/Mql/Lang/Mql.mqh new file mode 100644 index 0000000..36d8739 --- /dev/null +++ b/Documents/Resources/ZeroMQ/Includes/Mql/Lang/Mql.mqh @@ -0,0 +1,155 @@ +//+------------------------------------------------------------------+ +//| Module: Lang/Mql.mqh | +//| This file is part of the mql4-lib project: | +//| https://github.com/dingmaotu/mql4-lib | +//| | +//| Copyright 2017 Li Ding | +//| | +//| Licensed under the Apache License, Version 2.0 (the "License"); | +//| you may not use this file except in compliance with the License. | +//| You may obtain a copy of the License at | +//| | +//| http://www.apache.org/licenses/LICENSE-2.0 | +//| | +//| Unless required by applicable law or agreed to in writing, | +//| software distributed under the License is distributed on an | +//| "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, | +//| either express or implied. | +//| See the License for the specific language governing permissions | +//| and limitations under the License. | +//+------------------------------------------------------------------+ +#property strict +#include "Error.mqh" +//+------------------------------------------------------------------+ +//| Mql language specific methods | +//+------------------------------------------------------------------+ +class Mql +{ +public: + static int getLastError() { return GetLastError(); } + static string getErrorMessage(int errorCode) { return GetErrorDescription(errorCode); } + + //--- Prefer global DoubleToString function + static string doubleToString(double value, int precision) { return DoubleToString(value, precision); } + //--- Adapted from stdlib.mq4 by using `StringSetCharacter` instead of `StringSetChar` + static string integerToHexString(int value) + { + static const string digits = "0123456789ABCDEF"; + string hex = "00000000"; + int digit, shift = 28; + for (int i = 0; i < 8; i++) + { + digit = (value >> shift) & 0x0F; + StringSetCharacter(hex, i, digits[digit]); + shift -= 4; + } + return (hex); + } + //--- Prefer Canvas/Canvas.mqh XRGB + static int rgb(int r, int g, int b) { return int(0xFF000000 | (uchar(r) << 16) | (uchar(g) << 8) | uchar(b)); } + + //--- Prefer Lang/Number.mqh Double::IsEqual + static bool isEqual(double a, double b) { return NormalizeDouble(a - b, 8) == 0; } + + static bool isStopped() { return IsStopped(); } + + static int getCodePage() { return MQLInfoInteger(MQL_CODEPAGE); } + static ENUM_PROGRAM_TYPE getProgramType() { return (ENUM_PROGRAM_TYPE)MQLInfoInteger(MQL_PROGRAM_TYPE); } + static bool isScript() { return Mql::getProgramType() == PROGRAM_SCRIPT; } + static bool isExpert() { return Mql::getProgramType() == PROGRAM_EXPERT; } + static bool isIndicator() { return Mql::getProgramType() == PROGRAM_INDICATOR; } + static bool isDllAllowed() { return MQLInfoInteger(MQL_DLLS_ALLOWED) != 0; } + static bool isTradeAllowed() { return MQLInfoInteger(MQL_TRADE_ALLOWED) != 0; } + static bool isSignalsAllowed() { return MQLInfoInteger(MQL_SIGNALS_ALLOWED) != 0; } + static bool isDebug() { return MQLInfoInteger(MQL_DEBUG) != 0; } + static bool isProfiling() { return MQLInfoInteger(MQL_PROFILER) != 0; } + static bool isTesting() { return MQLInfoInteger(MQL_TESTER) != 0; } + static bool isOptimizing() { return MQLInfoInteger(MQL_OPTIMIZATION) != 0; } + static bool isVisual() { return MQLInfoInteger(MQL_VISUAL_MODE) != 0; } + static bool isFrameMode() { return MQLInfoInteger(MQL_FRAME_MODE) != 0; } + static ENUM_LICENSE_TYPE getLicenseType() { return (ENUM_LICENSE_TYPE)MQLInfoInteger(MQL_LICENSE_TYPE); } + static bool isFreeLicense() { return Mql::getLicenseType() == LICENSE_FREE; } + static bool isDemoLicense() { return Mql::getLicenseType() == LICENSE_DEMO; } + static bool isFullLicense() { return Mql::getLicenseType() == LICENSE_FULL; } + static bool isTimeLicense() { return Mql::getLicenseType() == LICENSE_TIME; } + + static string getProgramName() { return MQLInfoString(MQL_PROGRAM_NAME); } + static string getProgramPath() { return MQLInfoString(MQL_PROGRAM_PATH); } +}; +//+------------------------------------------------------------------+ +//| Object getter/setter generator | +//| ObjectAttr generates: | +//| 1. private member m_property | +//| 2. public method setProperty | +//| 3. public method getProperty | +//| ObjectAttrBool is specific to boolean type properties: | +//| 1. private member m_isProperty | +//| 2. public method setProperty | +//| 3. public method isProperty | +//| Use *Read or *Write versions for read only or write only | +//| properties | +//+------------------------------------------------------------------+ +#define ObjectAttr(Type, Private, Public) \ +public: \ + Type get##Public() const { return m_##Private; } \ + void set##Public(Type value) { m_##Private = value; } \ + \ +private: \ + Type m_##Private + +#define ObjectAttrRead(Type, Private, Public) \ +public: \ + Type get##Public() const { return m_##Private; } \ + \ +private: \ + Type m_##Private + +#define ObjectAttrWrite(Type, Private, Public) \ +public: \ + void set##Public(Type value) { m_##Private = value; } \ + \ +private: \ + Type m_##Private + +#define ObjectAttrBool(Public) \ +public: \ + bool is##Public() const { return m_is##Public; } \ + void set##Public(bool value) { m_is##Public = value; } \ + \ +private: \ + bool m_is##Public + +#define ObjectAttrBoolRead(Public) \ +public: \ + bool is##Public() const { return m_is##Public; } \ + \ +private: \ + bool m_is##Public + +#define ObjectAttrBoolWrite(Public) \ +public: \ + void set##Public(bool value) { m_is##Public = value; } \ + \ +private: \ + bool m_##Private //+------------------------------------------------------------------+ + //| Print debug messages: only generate code for debugging runs | + //+------------------------------------------------------------------+ +#ifdef _DEBUG +#define Debug(msg) PrintFormat(">>> DEBUG[%s,%d,%s]: %s", __FILE__, __LINE__, __FUNCTION__, msg); +#else +#define Debug(msg) +#endif +//+------------------------------------------------------------------+ +//| Execute some code in the global scope | +//+------------------------------------------------------------------+ +#define BEGIN_EXECUTE(Name) \ + class __Execute##Name \ + { \ + public: \ + __Execute##Name() \ + { +#define END_EXECUTE(Name) \ + } \ + } \ + __execute##Name; +//+------------------------------------------------------------------+ diff --git a/Documents/Resources/ZeroMQ/Includes/Mql/Lang/Native.mqh b/Documents/Resources/ZeroMQ/Includes/Mql/Lang/Native.mqh new file mode 100644 index 0000000..b640607 --- /dev/null +++ b/Documents/Resources/ZeroMQ/Includes/Mql/Lang/Native.mqh @@ -0,0 +1,215 @@ +//+------------------------------------------------------------------+ +//| Module: Lang/Native.mqh | +//| This file is part of the mql4-lib project: | +//| https://github.com/dingmaotu/mql4-lib | +//| | +//| Copyright 2016-2017 Li Ding | +//| | +//| Licensed under the Apache License, Version 2.0 (the "License"); | +//| you may not use this file except in compliance with the License. | +//| You may obtain a copy of the License at | +//| | +//| http://www.apache.org/licenses/LICENSE-2.0 | +//| | +//| Unless required by applicable law or agreed to in writing, | +//| software distributed under the License is distributed on an | +//| "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, | +//| either express or implied. | +//| See the License for the specific language governing permissions | +//| and limitations under the License. | +//+------------------------------------------------------------------+ +#property strict + +// Assume MT5 is 64bit, which is the default. +// Even though MT5 can be 32bit, there is no way to detect this +// by using preprocessor macros. Instead, MetaQuotes provides a +// function called IsX64 to detect this dynamically + +// This is just absurd. Why do you want to know the bitness of +// the runtime? To define pointer related entities at compile time! +// All integer types in MQL is uniform on both 32bit or 64bit +// architectures, so it is almost useless to have a runtime function IsX64. + +// Why not a __X64__? +#ifdef __MQL5__ +#define __X64__ +#endif + +#ifdef __X64__ +#define intptr_t long +#define uintptr_t ulong +#define size_t long +#else +#define intptr_t int +#define uintptr_t uint +#define size_t int +#endif + +#import "kernel32.dll" +void RtlMoveMemory(intptr_t dest, const uchar &array[], size_t length); +void RtlMoveMemory(uchar &array[], intptr_t src, size_t length); +void RtlMoveMemory(intptr_t dest, const MqlRates &array[], size_t length); +void RtlMoveMemory(MqlRates &array[], intptr_t src, size_t length); +void RtlMoveMemory(intptr_t dest, const MqlTick &value, size_t length); +void RtlMoveMemory(MqlTick &value, intptr_t src, size_t length); +void RtlMoveMemory(intptr_t &dest, intptr_t src, size_t length); +int lstrlen(intptr_t psz); +int lstrlenW(intptr_t psz); +uintptr_t lstrcpynW(string &s1, uintptr_t s2, int length); +uintptr_t lstrcpynW(uintptr_t s1, string &s2, int length); + +int MultiByteToWideChar(uint codePage, + uint flags, + const intptr_t multiByteString, + int lengthMultiByte, + string &str, + int length); +#import +//+------------------------------------------------------------------+ +//| Copy the memory contents pointed by src to array | +//| array parameter should be initialized to the desired size | +//| Need to import RtlMoveMemory with appropriate parameter type T | +//+------------------------------------------------------------------+ +template +void ArrayFromPointer(T &array[], intptr_t src, int count = WHOLE_ARRAY) +{ + int size = (count == WHOLE_ARRAY) ? ArraySize(array) : count; + RtlMoveMemory(array, src, (size_t)(size * sizeof(T))); +} +//+------------------------------------------------------------------+ +//| Copy array to the memory pointed by dest | +//| Need to import RtlMoveMemory with appropriate parameter type T | +//+------------------------------------------------------------------+ +template +void ArrayToPointer(const T &array[], intptr_t dest, int count = WHOLE_ARRAY) +{ + int size = (count == WHOLE_ARRAY) ? ArraySize(array) : count; + RtlMoveMemory(dest, array, (size_t)(size * sizeof(T))); +} +//+------------------------------------------------------------------+ +//| Copy the memory contents pointed by src to value type T | +//| Need to import RtlMoveMemory with appropriate parameter type T | +//+------------------------------------------------------------------+ +template +void ValueFromPointer(T &value, intptr_t src) +{ + RtlMoveMemory(value, src, (size_t)sizeof(T)); +} +//+------------------------------------------------------------------+ +//| Copy value to the memory pointed by dest | +//| Need to import RtlMoveMemory with appropriate parameter type T | +//+------------------------------------------------------------------+ +template +void ValueToPointer(const T &value, intptr_t dest) +{ + RtlMoveMemory(dest, value, (size_t)sizeof(T)); +} +//+------------------------------------------------------------------+ +//| For void** type, dereference a level to void* | +//+------------------------------------------------------------------+ +intptr_t DereferencePointer(intptr_t pointer) +{ + intptr_t res = 0; + RtlMoveMemory(res, pointer, sizeof(intptr_t)); + return res; +} +//+------------------------------------------------------------------+ +//| Read a valid wide character string to the MQL environment | +//+------------------------------------------------------------------+ +string StringFromPointer(intptr_t psz, int len = 0) +{ + if (len < 0) + return NULL; + if (len == 0) + { + len = lstrlenW(psz); + } + string res; + StringInit(res, len + 1); + lstrcpynW(res, psz, len + 1); + return res; +} +//+------------------------------------------------------------------+ +//| Get the pointer address of a string | +//+------------------------------------------------------------------+ +uintptr_t StringToPointer(string &s) +{ + return lstrcpynW(s, 0, 0); +} +//+------------------------------------------------------------------+ +//| Read a valid utf-8 string to the MQL environment | +//| With this function, there is no need to copy the string to char | +//| array, and convert with CharArrayToString | +//+------------------------------------------------------------------+ +string StringFromUtf8Pointer(intptr_t psz, int len) +{ + if (len < 0) + return NULL; + string res; + int required = MultiByteToWideChar(CP_UTF8, 0, psz, len, res, 0); + // need to include the NULL terminating character + StringInit(res, required + 1); + int rlen = MultiByteToWideChar(CP_UTF8, 0, psz, len, res, required); + return rlen != required ? NULL : res; +} +//+------------------------------------------------------------------+ +//| for null-terminated string | +//+------------------------------------------------------------------+ +string StringFromUtf8Pointer(intptr_t psz) +{ + if (psz == 0) + return NULL; + int len = lstrlen(psz); + if (len == 0) + return NULL; + return StringFromUtf8Pointer(psz, len); +} +//+------------------------------------------------------------------+ +//| Convert a utf-8 byte array to a string | +//+------------------------------------------------------------------+ +string StringFromUtf8(const uchar &utf8[]) +{ + return CharArrayToString(utf8, 0, -1, CP_UTF8); +} +//+------------------------------------------------------------------+ +//| Convert a char array to a string (overload for char arrays) | +//+------------------------------------------------------------------+ +string StringFromUtf8(const char &utf8[]) +{ + uchar temp[]; + int size = ArraySize(utf8); + ArrayResize(temp, size); + for (int i = 0; i < size; i++) + { + temp[i] = (uchar)utf8[i]; + } + return CharArrayToString(temp, 0, -1, CP_UTF8); +} +//+------------------------------------------------------------------+ +//| Convert a string to a utf-8 byte array | +//+------------------------------------------------------------------+ +void StringToUtf8(const string str, uchar &utf8[], bool ending = true) +{ + if (!ending && str == "") + return; + int count = ending ? -1 : StringLen(str); + StringToCharArray(str, utf8, 0, count, CP_UTF8); +} +//+------------------------------------------------------------------+ +//| Convert a string to a char array (overload for char arrays) | +//+------------------------------------------------------------------+ +void StringToUtf8(const string str, char &utf8[], bool ending = true) +{ + if (!ending && str == "") + return; + uchar temp[]; + int count = ending ? -1 : StringLen(str); + StringToCharArray(str, temp, 0, count, CP_UTF8); + int size = ArraySize(temp); + ArrayResize(utf8, size); + for (int i = 0; i < size; i++) + { + utf8[i] = (char)temp[i]; + } +} +//+------------------------------------------------------------------+ diff --git a/Documents/Resources/ZeroMQ/Includes/Socket.mqh b/Documents/Resources/ZeroMQ/Includes/Socket.mqh deleted file mode 100644 index a35a5c2..0000000 --- a/Documents/Resources/ZeroMQ/Includes/Socket.mqh +++ /dev/null @@ -1,276 +0,0 @@ -//+------------------------------------------------------------------+ -//| Module: Socket.mqh | -//| This file is part of the mql-zmq project: | -//| https://github.com/dingmaotu/mql-zmq | -//| | -//| Copyright 2016-2017 Li Ding | -//| | -//| Licensed under the Apache License, Version 2.0 (the "License"); | -//| you may not use this file except in compliance with the License. | -//| You may obtain a copy of the License at | -//| | -//| http://www.apache.org/licenses/LICENSE-2.0 | -//| | -//| Unless required by applicable law or agreed to in writing, | -//| software distributed under the License is distributed on an | -//| "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, | -//| either express or implied. | -//| See the License for the specific language governing permissions | -//| and limitations under the License. | -//+------------------------------------------------------------------+ -#property strict - -#include -#include -#include "Context.mqh" -#include "SocketOptions.mqh" -#include "ZmqMsg.mqh" - -//--- Socket types -#define ZMQ_PAIR 0 -#define ZMQ_PUB 1 -#define ZMQ_SUB 2 -#define ZMQ_REQ 3 -#define ZMQ_REP 4 -#define ZMQ_DEALER 5 -#define ZMQ_ROUTER 6 -#define ZMQ_PULL 7 -#define ZMQ_PUSH 8 -#define ZMQ_XPUB 9 -#define ZMQ_XSUB 10 -#define ZMQ_STREAM 11 - -//--- Message options -#define ZMQ_MORE 1 -#define ZMQ_SRCFD 2 // Deprecated -#define ZMQ_SHARED 3 - -//--- Send/recv options -#define ZMQ_DONTWAIT 1 -#define ZMQ_SNDMORE 2 - -//--- Socket transport events (TCP, IPC and TIPC only) -#define ZMQ_EVENT_CONNECTED 0x0001 -#define ZMQ_EVENT_CONNECT_DELAYED 0x0002 -#define ZMQ_EVENT_CONNECT_RETRIED 0x0004 -#define ZMQ_EVENT_LISTENING 0x0008 -#define ZMQ_EVENT_BIND_FAILED 0x0010 -#define ZMQ_EVENT_ACCEPTED 0x0020 -#define ZMQ_EVENT_ACCEPT_FAILED 0x0040 -#define ZMQ_EVENT_CLOSED 0x0080 -#define ZMQ_EVENT_CLOSE_FAILED 0x0100 -#define ZMQ_EVENT_DISCONNECTED 0x0200 -#define ZMQ_EVENT_MONITOR_STOPPED 0x0400 -#define ZMQ_EVENT_ALL 0xFFFF - -//--- I/O multiplexing -#define ZMQ_POLLIN 1 -#define ZMQ_POLLOUT 2 -// We only use 0MQ sockets on Windows -// So POLLERR and POLLPRI is of no use -#define ZMQ_POLLERR 4 -#define ZMQ_POLLPRI 8 - -#define ZMQ_POLLITEMS_DFLT 16 -//--- fd is SOCKET on Win32, which is defined as UINT_PTR -struct PollItem - { - intptr_t socket; - uintptr_t fd; - short events; - short revents; -#ifdef __X64__ - //--- note here that if the program runs on 64bit runtime, we need to pad the - //--- struct to align to 8 bytes - //--- thanks https://github.com/feng-ye for the solution to https://github.com/dingmaotu/mql-zmq/issues/14 - int __unused; -#endif - - bool hasInput() const {return(revents&ZMQ_POLLIN)!=0;} - bool hasOutput() const {return(revents&ZMQ_POLLOUT)!=0;} - }; -#import "libzmq.dll" -//+------------------------------------------------------------------+ -//| Sockets | -//+------------------------------------------------------------------+ -intptr_t zmq_socket(intptr_t context,int type); -int zmq_close(intptr_t s); -int zmq_bind(intptr_t s,const char &addr[]); -int zmq_connect(intptr_t s,const char &addr[]); -int zmq_unbind(intptr_t s,const char &addr[]); -int zmq_disconnect(intptr_t s,const char &addr[]); -int zmq_send(intptr_t s,const uchar &buf[],size_t len,int flags); -int zmq_send_const(intptr_t s,const uchar &buf[],size_t len,int flags); -int zmq_recv(intptr_t s,uchar &buf[],size_t len,int flags); -int zmq_socket_monitor(intptr_t s,const char &addr[],int events); -//+------------------------------------------------------------------+ -//| Message | -//+------------------------------------------------------------------+ -int zmq_msg_send(zmq_msg_t &msg,intptr_t s,int flags); -int zmq_msg_recv(zmq_msg_t &msg,intptr_t s,int flags); -//+------------------------------------------------------------------+ -//| I/O multiplexing | -//+------------------------------------------------------------------+ -int zmq_poll(PollItem &items[],int nitems,long timeout); -//+------------------------------------------------------------------+ -//| Message proxying | -//+------------------------------------------------------------------+ -int zmq_proxy(intptr_t frontend_ref,intptr_t backend_ref,intptr_t capture_ref); -int zmq_proxy_steerable(intptr_t frontend_ref,intptr_t backend_ref,intptr_t capture_ref,intptr_t control_ref); -#import -//+------------------------------------------------------------------+ -//| Wraps a 0MQ socket | -//+------------------------------------------------------------------+ -class Socket: public SocketOptions - { -public: - Socket(const Context &ctx,int type):SocketOptions(zmq_socket(ctx.ref(),type)){} - virtual ~Socket() {if(0!=zmq_close(m_ref)){Debug(StringFormat("Failed to close socket 0x%0X",m_ref));}} - - // for better cooperation between objects - intptr_t ref() const {return m_ref;} - - bool valid() const {return m_ref!=0;} - - //--- see Zmq::error() if any of the following command failed - //--- connection management - bool bind(string addr); - bool unbind(string addr); - bool connect(string addr); - bool disconnect(string addr); - - //--- send raw bytes - bool send(const uchar &buf[],bool nowait=false) {return -1!=zmq_send(m_ref,buf,ArraySize(buf),nowait?ZMQ_DONTWAIT:0);} - bool sendConst(const uchar &buf[],bool nowait=false) {return -1!=zmq_send_const(m_ref,buf,ArraySize(buf),nowait?ZMQ_DONTWAIT:0);} - - //--- send ZmqMsg - bool send(ZmqMsg &msg,bool nowait=false) {return -1!=zmq_msg_send(msg,m_ref,nowait?ZMQ_DONTWAIT:0);} - //--- send string - bool send(string msg,bool nowait=false) {ZmqMsg m(msg); return send(m,nowait);} - //--- send empty - bool send(bool nowait=false) {ZmqMsg m; return send(m,nowait);} - - //--- same as above 5 but for multipart messages - bool sendMore(const uchar &buf[],bool nowait=false); - bool sendConstMore(const uchar &buf[],bool nowait=false); - bool sendMore(ZmqMsg &msg,bool nowait=false) - { - int flags=ZMQ_SNDMORE; - if(nowait) flags|=ZMQ_DONTWAIT; - return -1!=zmq_msg_send(msg,m_ref,flags); - } - bool sendMore(string msg,bool nowait=false) {ZmqMsg m(msg); return sendMore(m,nowait);} - bool sendMore(bool nowait=false) {ZmqMsg m; return sendMore(m,nowait);} - - //--- receive packets - bool recv(uchar &buf[],bool nowait=false) {return -1!=zmq_recv(m_ref,buf,ArraySize(buf),nowait?ZMQ_DONTWAIT:0);} - bool recv(ZmqMsg &msg,bool nowait=false) {return -1!=zmq_msg_recv(msg,m_ref,nowait?ZMQ_DONTWAIT:0);} - - //--- monitor socket events - bool monitor(string addr,int events); - - //--- proxy - static bool proxy(Socket *frontend,Socket *backend,Socket *capture); - static bool proxySteerable(Socket *frontend,Socket *backend,Socket *capture,Socket *control); - - //--- poll - static int poll(PollItem &arr[],long timeout); - - //--- fill a poll item for this socket - void fillPollItem(PollItem &item,short events); - }; -//+------------------------------------------------------------------+ -//| | -//+------------------------------------------------------------------+ -bool Socket::bind(string addr) - { - char arr[]; - StringToUtf8(addr,arr); - bool res=(0==zmq_bind(m_ref,arr)); - ArrayFree(arr); - return res; - } -//+------------------------------------------------------------------+ -//| | -//+------------------------------------------------------------------+ -bool Socket::unbind(string addr) - { - char arr[]; - StringToUtf8(addr,arr); - bool res=(0==zmq_unbind(m_ref,arr)); - ArrayFree(arr); - return res; - } -//+------------------------------------------------------------------+ -//| | -//+------------------------------------------------------------------+ -bool Socket::connect(string addr) - { - char arr[]; - StringToUtf8(addr,arr); - bool res=(0==zmq_connect(m_ref,arr)); - ArrayFree(arr); - return res; - } -//+------------------------------------------------------------------+ -//| | -//+------------------------------------------------------------------+ -bool Socket::disconnect(string addr) - { - char arr[]; - StringToUtf8(addr,arr); - bool res=(0==zmq_disconnect(m_ref,arr)); - ArrayFree(arr); - return res; - } -//+------------------------------------------------------------------+ -//| | -//+------------------------------------------------------------------+ -bool Socket::monitor(string addr,int events) - { - uchar str[]; - StringToUtf8(addr,str); - bool res=(0==zmq_socket_monitor(m_ref,str,events)); - ArrayFree(str); - return res; - } -//+------------------------------------------------------------------+ -//| | -//+------------------------------------------------------------------+ -bool Socket::proxy(Socket *frontend,Socket *backend,Socket *capture) - { - intptr_t frontend_ref= CheckPointer(frontend)==POINTER_DYNAMIC?frontend.ref():0; - intptr_t backend_ref = CheckPointer(backend)==POINTER_DYNAMIC?backend.ref():0; - intptr_t capture_ref=CheckPointer(capture)==POINTER_DYNAMIC?capture.ref():0; - return 0==zmq_proxy(frontend_ref, backend_ref, capture_ref); - } -//+------------------------------------------------------------------+ -//| | -//+------------------------------------------------------------------+ -bool Socket::proxySteerable(Socket *frontend,Socket *backend,Socket *capture,Socket *control) - { - intptr_t frontend_ref= CheckPointer(frontend)==POINTER_DYNAMIC?frontend.ref():0; - intptr_t backend_ref = CheckPointer(backend)==POINTER_DYNAMIC?backend.ref():0; - intptr_t capture_ref=CheckPointer(capture)==POINTER_DYNAMIC?capture.ref():0; - intptr_t control_ref=CheckPointer(control)==POINTER_DYNAMIC?control.ref():0; - return 0==zmq_proxy_steerable(frontend_ref, backend_ref, capture_ref, control_ref); - } -//+------------------------------------------------------------------+ -//| poll for events. timeout is milliseconds (-1 for indefinite wait | -//| and 0 for immediate return) | -//+------------------------------------------------------------------+ -int Socket::poll(PollItem &arr[],long timeout) - { - return zmq_poll(arr,ArraySize(arr),timeout); - } -//+------------------------------------------------------------------+ -//| fill a poll item for this socket | -//+------------------------------------------------------------------+ -void Socket::fillPollItem(PollItem &item,short events) - { - item.socket=m_ref; - item.fd=0; - item.events=events; - item.revents=0; - } -//+------------------------------------------------------------------+ diff --git a/Documents/Resources/ZeroMQ/Includes/SocketOptions.mqh b/Documents/Resources/ZeroMQ/Includes/SocketOptions.mqh deleted file mode 100644 index f712584..0000000 --- a/Documents/Resources/ZeroMQ/Includes/SocketOptions.mqh +++ /dev/null @@ -1,358 +0,0 @@ -//+------------------------------------------------------------------+ -//| Module: SocketOptions.mqh | -//| This file is part of the mql-zmq project: | -//| https://github.com/dingmaotu/mql-zmq | -//| | -//| Copyright 2016-2017 Li Ding | -//| | -//| Licensed under the Apache License, Version 2.0 (the "License"); | -//| you may not use this file except in compliance with the License. | -//| You may obtain a copy of the License at | -//| | -//| http://www.apache.org/licenses/LICENSE-2.0 | -//| | -//| Unless required by applicable law or agreed to in writing, | -//| software distributed under the License is distributed on an | -//| "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, | -//| either express or implied. | -//| See the License for the specific language governing permissions | -//| and limitations under the License. | -//+------------------------------------------------------------------+ -#property strict - -#include - -#import "libzmq.dll" -// We can overload the same function for different data types -// as in the C level the optval paramter is just a pointer -#define SOCKOPT_OVERLOAD_ARRAY(TYPE) \ -int zmq_setsockopt(intptr_t s,int option,const TYPE &optval[],\ - size_t optvallen);\ -int zmq_getsockopt(intptr_t s,int option,TYPE &optval[],\ - size_t &optvallen);\ - -#define SOCKOPT_OVERLOAD(TYPE) \ -int zmq_setsockopt(intptr_t s,int option,const TYPE &optval,\ - size_t optvallen);\ -int zmq_getsockopt(intptr_t s,int option,TYPE &optval,\ - size_t &optvallen);\ - -SOCKOPT_OVERLOAD_ARRAY(uchar) -SOCKOPT_OVERLOAD(long) -SOCKOPT_OVERLOAD(ulong) -SOCKOPT_OVERLOAD(int) -SOCKOPT_OVERLOAD(uint) -#import - -// Socket options -#define ZMQ_AFFINITY 4 -#define ZMQ_IDENTITY 5 -#define ZMQ_SUBSCRIBE 6 -#define ZMQ_UNSUBSCRIBE 7 -#define ZMQ_RATE 8 -#define ZMQ_RECOVERY_IVL 9 -#define ZMQ_SNDBUF 11 -#define ZMQ_RCVBUF 12 -#define ZMQ_RCVMORE 13 -#define ZMQ_FD 14 -#define ZMQ_EVENTS 15 -#define ZMQ_TYPE 16 -#define ZMQ_LINGER 17 -#define ZMQ_RECONNECT_IVL 18 -#define ZMQ_BACKLOG 19 -#define ZMQ_RECONNECT_IVL_MAX 21 -#define ZMQ_MAXMSGSIZE 22 -#define ZMQ_SNDHWM 23 -#define ZMQ_RCVHWM 24 -#define ZMQ_MULTICAST_HOPS 25 -#define ZMQ_RCVTIMEO 27 -#define ZMQ_SNDTIMEO 28 -#define ZMQ_LAST_ENDPOINT 32 -#define ZMQ_ROUTER_MANDATORY 33 -#define ZMQ_TCP_KEEPALIVE 34 -#define ZMQ_TCP_KEEPALIVE_CNT 35 -#define ZMQ_TCP_KEEPALIVE_IDLE 36 -#define ZMQ_TCP_KEEPALIVE_INTVL 37 -#define ZMQ_IMMEDIATE 39 -#define ZMQ_XPUB_VERBOSE 40 -#define ZMQ_ROUTER_RAW 41 -#define ZMQ_IPV6 42 -#define ZMQ_MECHANISM 43 -#define ZMQ_PLAIN_SERVER 44 -#define ZMQ_PLAIN_USERNAME 45 -#define ZMQ_PLAIN_PASSWORD 46 -#define ZMQ_CURVE_SERVER 47 -#define ZMQ_CURVE_PUBLICKEY 48 -#define ZMQ_CURVE_SECRETKEY 49 -#define ZMQ_CURVE_SERVERKEY 50 -#define ZMQ_PROBE_ROUTER 51 -#define ZMQ_REQ_CORRELATE 52 -#define ZMQ_REQ_RELAXED 53 -#define ZMQ_CONFLATE 54 -#define ZMQ_ZAP_DOMAIN 55 -#define ZMQ_ROUTER_HANDOVER 56 -#define ZMQ_TOS 57 -#define ZMQ_CONNECT_RID 61 -#define ZMQ_GSSAPI_SERVER 62 -#define ZMQ_GSSAPI_PRINCIPAL 63 -#define ZMQ_GSSAPI_SERVICE_PRINCIPAL 64 -#define ZMQ_GSSAPI_PLAINTEXT 65 -#define ZMQ_HANDSHAKE_IVL 66 -#define ZMQ_SOCKS_PROXY 68 -#define ZMQ_XPUB_NODROP 69 -#define ZMQ_BLOCKY 70 -#define ZMQ_XPUB_MANUAL 71 -#define ZMQ_XPUB_WELCOME_MSG 72 -#define ZMQ_STREAM_NOTIFY 73 -#define ZMQ_INVERT_MATCHING 74 -#define ZMQ_HEARTBEAT_IVL 75 -#define ZMQ_HEARTBEAT_TTL 76 -#define ZMQ_HEARTBEAT_TIMEOUT 77 -#define ZMQ_XPUB_VERBOSER 78 -#define ZMQ_CONNECT_TIMEOUT 79 -#define ZMQ_TCP_MAXRT 80 -#define ZMQ_THREAD_SAFE 81 -#define ZMQ_MULTICAST_MAXTPDU 84 -#define ZMQ_VMCI_BUFFER_SIZE 85 -#define ZMQ_VMCI_BUFFER_MIN_SIZE 86 -#define ZMQ_VMCI_BUFFER_MAX_SIZE 87 -#define ZMQ_VMCI_CONNECT_TIMEOUT 88 -#define ZMQ_USE_FD 89 -//+------------------------------------------------------------------+ -//| A dedicated class to get/set socket options | -//+------------------------------------------------------------------+ -class SocketOptions - { -protected: - intptr_t m_ref; - -#define SOCKOPT_WRAP_ARRAY(TYPE) \ - bool setOption(int option,const TYPE &value[],size_t len) {return 0==zmq_setsockopt(m_ref,option,value,len);}\ - bool getOption(int option,TYPE &value[],size_t &len) {return 0==zmq_getsockopt(m_ref,option,value,len);} - -#define SOCKOPT_WRAP(TYPE) \ - bool setOption(int option,TYPE value) {return 0==zmq_setsockopt(m_ref,option,value,sizeof(TYPE));}\ - bool getOption(int option,TYPE &value) {size_t s=sizeof(TYPE); return 0==zmq_getsockopt(m_ref,option,value,s);} - - SOCKOPT_WRAP_ARRAY(uchar) - SOCKOPT_WRAP(int) - SOCKOPT_WRAP(uint) - SOCKOPT_WRAP(long) - SOCKOPT_WRAP(ulong) - - bool setStringOption(int option,string value,bool ending=true); - bool getStringOption(int option,string &value,size_t length=1024); - SocketOptions(intptr_t ref):m_ref(ref){} -public: - //--- option templates - //--- various integer options -#define SOCKOPT_GET(TYPE, NAME, MACRO) \ - bool get##NAME(TYPE &value) {return getOption(MACRO,value);} -#define SOCKOPT_SET(TYPE, NAME, MACRO) \ - bool set##NAME(TYPE value) {return setOption(MACRO,value);} -#define SOCKOPT(TYPE,NAME,MACRO) \ - SOCKOPT_GET(TYPE,NAME,MACRO) \ - SOCKOPT_SET(TYPE,NAME,MACRO) - - //--- boolean options -#define SOCKOPT_GET_BOOL(NAME, MACRO) \ - bool is##NAME(bool &value) {int v; bool res=getOption(MACRO,v); value=(v==1);return res;} -#define SOCKOPT_SET_BOOL(NAME, MACRO) \ - bool set##NAME(bool value) {return setOption(MACRO,value?1:0);} -#define SOCKOPT_BOOL(NAME,MACRO) \ - SOCKOPT_GET_BOOL(NAME,MACRO) \ - SOCKOPT_SET_BOOL(NAME,MACRO) - - //--- null-terminated string options -#define SOCKOPT_GET_NTSTR(NAME,MACRO) \ - bool get##NAME(string &value) {return getStringOption(MACRO,value);} -#define SOCKOPT_SET_NTSTR(NAME,MACRO) \ - bool set##NAME(string value) {return setStringOption(MACRO,value);} -#define SOCKOPT_NTSTR(NAME,MACRO) \ - SOCKOPT_GET_NTSTR(NAME,MACRO) \ - SOCKOPT_SET_NTSTR(NAME,MACRO) - - //--- bytes array or string converted options -#define SOCKOPT_SET_BYTES(OptionName,Macro) \ - bool set##OptionName(const uchar &value[]) {return setOption(Macro,value,(size_t)ArraySize(value));} \ - bool set##OptionName(string value) {return setStringOption(Macro,value,false);} -#define SOCKOPT_GET_BYTES(OptionName,Macro,InitSize) \ - bool get##OptionName(uchar &value[]) {size_t len=(size_t)InitSize; ArrayResize(value,(int)len); bool res=getOption(Macro,value,len); if(res){ArrayResize(value,(int)len);}return res;} \ - bool get##OptionName(string &value) {return getStringOption(Macro,value,InitSize);} -#define SOCKOPT_BYTES(OptionName,Macro,InitSize) \ - SOCKOPT_SET_BYTES(OptionName,Macro) \ - SOCKOPT_GET_BYTES(OptionName,Macro,InitSize) - - //--- for curve key - //--- NOTE that the length of the key array must be 32. - //--- since some versions of mt4 and newer versions of mt5 will report error - //--- when the length of the array is specified, so the length specification is removed -#define SOCKOPT_CURVE_KEY(KeyType,Macro) \ - bool getCurve##KeyType##Key(uchar &key[]) {size_t len=32; return getOption(Macro,key,len);} \ - bool getCurve##KeyType##Key(string &key) {return getStringOption(Macro,key,41);} \ - bool setCurve##KeyType##Key(const uchar &key[]) {return setOption(Macro,key,32);} \ - bool setCurve##KeyType##Key(string key) {return setStringOption(Macro,key);} - - SOCKOPT_GET(int,Type,ZMQ_TYPE) - SOCKOPT(ulong,Affinity,ZMQ_AFFINITY) //64bit bitmask - SOCKOPT(int,BackLog,ZMQ_BACKLOG) // number of connections - SOCKOPT(int,Timeout,ZMQ_CONNECT_TIMEOUT) // milliseconds - SOCKOPT_GET_BOOL(ThreadSafe,ZMQ_THREAD_SAFE) - - SOCKOPT_SET_BOOL(Conflate,ZMQ_CONFLATE) // only for ZMQ_PULL, ZMQ_PUSH, ZMQ_SUB, ZMQ_PUB, ZMQ_DEALER types - - SOCKOPT_GET(int,Events,ZMQ_EVENTS); // bitmask of ZMQ_POLLIN, ZMQ_POLLOUT - - SOCKOPT_GET(uintptr_t,FileDescriptor,ZMQ_FD) - - SOCKOPT_GET(int,Mechanism,ZMQ_MECHANISM) // current security mechanism - - //--- plain - SOCKOPT_NTSTR(PlainUsername,ZMQ_PLAIN_USERNAME) - SOCKOPT_NTSTR(PlainPassword,ZMQ_PLAIN_PASSWORD) - SOCKOPT_BOOL(PlainServer,ZMQ_PLAIN_SERVER) - - //--- gssapi: this is not supported in this binding. Following methods will FAIL if you invoke them - SOCKOPT_BOOL(GssApiPlainText,ZMQ_GSSAPI_PLAINTEXT) - SOCKOPT_BOOL(GssApiServer,ZMQ_GSSAPI_SERVER) - SOCKOPT_NTSTR(GssApiPrincipal,ZMQ_GSSAPI_PRINCIPAL) - SOCKOPT_NTSTR(GssApiServicePrincipal,ZMQ_GSSAPI_SERVICE_PRINCIPAL) - - //--- curve - SOCKOPT_CURVE_KEY(Public,ZMQ_CURVE_PUBLICKEY) - SOCKOPT_CURVE_KEY(Secret,ZMQ_CURVE_SECRETKEY) - SOCKOPT_CURVE_KEY(Server,ZMQ_CURVE_SERVERKEY) - - SOCKOPT_SET_BOOL(CurveServer,ZMQ_CURVE_SERVER) - - SOCKOPT_GET_NTSTR(LastEndpoint,ZMQ_LAST_ENDPOINT) - - SOCKOPT(int,HandshakeInterval,ZMQ_HANDSHAKE_IVL) // milliseconds - SOCKOPT_SET(int,HeartbeatInterval,ZMQ_HEARTBEAT_IVL) // milliseconds - SOCKOPT_SET(int,HeartbeatTimeout,ZMQ_HEARTBEAT_TIMEOUT) // milliseconds - SOCKOPT_SET(int,HeartbeatTTL,ZMQ_HEARTBEAT_TTL) // milliseconds - - SOCKOPT_BOOL(Immediate,ZMQ_IMMEDIATE) - SOCKOPT_BOOL(Ipv6,ZMQ_IPV6) //--- ZMQ_IPV4ONLY is deprecated, use this instead - SOCKOPT(int,Linger,ZMQ_LINGER) // milliseconds - SOCKOPT(long,MaxMessageSize,ZMQ_MAXMSGSIZE) - - //--- multicast - SOCKOPT(int,MulticastHops,ZMQ_MULTICAST_HOPS) // hops - SOCKOPT(int,MulticastMaxTPDU,ZMQ_MULTICAST_MAXTPDU) // bytes - SOCKOPT(int,MulticastRate,ZMQ_RATE) // kilobits per second - SOCKOPT(int,RecoveryInterval,ZMQ_RECOVERY_IVL) // multicast recovery interval - - //--- there is a problem here: FileDescriptor should be SOCKET type on Windows, - //--- while in the zmq doc it is a int. Possible error in the doc - SOCKOPT(uintptr_t,UseFileDescriptor,ZMQ_USE_FD) - - SOCKOPT_SET_BOOL(ProbeRouter,ZMQ_PROBE_ROUTER) // only for ZMQ_ROUTER, ZMQ_DEALER, ZMQ_REQ - - SOCKOPT(int,ReceiveBuffer,ZMQ_RCVBUF) // bytes - SOCKOPT(int,ReceiveHighWaterMark,ZMQ_RCVHWM) // messages - SOCKOPT(int,ReceiveTimeout,ZMQ_RCVTIMEO) // milliseconds - SOCKOPT(int,SendBuffer,ZMQ_SNDBUF) // bytes - SOCKOPT(int,SendHighWaterMark,ZMQ_SNDHWM) // messages - SOCKOPT(int,SendTimeout,ZMQ_SNDTIMEO) - - SOCKOPT_GET_BOOL(ReceiveMore,ZMQ_RCVMORE) - - SOCKOPT(int,ReconnectInterval,ZMQ_RECONNECT_IVL) // milliseconds - SOCKOPT(int,ReconnectIntervalMax,ZMQ_RECONNECT_IVL_MAX) // milliseconds - - //--- only for ZMQ_REQ - SOCKOPT_SET_BOOL(RequestCorrelated,ZMQ_REQ_CORRELATE) - SOCKOPT_SET_BOOL(RequestRelaxed,ZMQ_REQ_RELAXED) - - //--- only for ZMQ_SUB - SOCKOPT_SET_BYTES(Subscribe,ZMQ_SUBSCRIBE) - SOCKOPT_SET_BYTES(Unsubscribe,ZMQ_UNSUBSCRIBE) - - //--- convenience methods - bool subscribe(string channel) {return setSubscribe(channel);} - bool unsubscribe(string channel) {return setUnsubscribe(channel);} - - //--- only for ZMQ_XSUB - SOCKOPT_BOOL(XpubVerbose,ZMQ_XPUB_VERBOSE) - SOCKOPT_BOOL(XpubVerboser,ZMQ_XPUB_VERBOSER) - SOCKOPT_BOOL(XpubManual,ZMQ_XPUB_MANUAL) - SOCKOPT_BOOL(XpubNoDrop,ZMQ_XPUB_NODROP) // also for ZMQ_PUB - SOCKOPT_SET_BYTES(XpubWelcomeMessage,ZMQ_XPUB_WELCOME_MSG) - - SOCKOPT_BOOL(InvertMatching,ZMQ_INVERT_MATCHING) //--- only for ZMQ_PUB, ZMQ_XPUB, ZMQ_SUB - - //--- only for ZMQ_ROUTER - SOCKOPT_SET_BOOL(RouterHandover,ZMQ_ROUTER_HANDOVER) - SOCKOPT_SET_BOOL(RouterMandatory,ZMQ_ROUTER_MANDATORY) - SOCKOPT_SET_BOOL(RouterRaw,ZMQ_ROUTER_RAW) - - //--- only for ZMQ_STREAM - SOCKOPT_SET_BOOL(StreamNotify,ZMQ_STREAM_NOTIFY) - - //--- only for ZMQ_ROUTER, ZMQ_STREAM - SOCKOPT_SET_BYTES(ConnectRid,ZMQ_CONNECT_RID) - - //--- only for ZMQ_REP, ZMQ_REQ, ZMQ_ROUTER, ZMQ_DEALER - SOCKOPT_BYTES(Identity,ZMQ_IDENTITY,255) - - //--- tcp - SOCKOPT(int,TcpKeepAlive,ZMQ_TCP_KEEPALIVE) - SOCKOPT(int,TcpKeepAliveCount,ZMQ_TCP_KEEPALIVE_CNT) - SOCKOPT(int,TcpKeepAliveIdle,ZMQ_TCP_KEEPALIVE_IDLE) - SOCKOPT(int,TcpKeepAliveInterval,ZMQ_TCP_KEEPALIVE_INTVL) - SOCKOPT(int,TcpMaxRetransmitTimeout,ZMQ_TCP_MAXRT) - - SOCKOPT(int,TypeOfService,ZMQ_TOS) // IP_TOS - - //--- ZMQ_TCP_ACCEPT_FILTER - //--- ZMQ_IPC_FILTER_GID - //--- ZMQ_IPC_FILTER_PID - //--- ZMQ_IPC_FILTER_UID - //--- are deprecated in favor of ZAP API and ip address whitelisting/blacklisting - SOCKOPT_NTSTR(ZapDomain,ZMQ_ZAP_DOMAIN) - - //--- only for vmci transport - SOCKOPT(ulong,VmciBufferSize,ZMQ_VMCI_BUFFER_SIZE) // bytes - SOCKOPT(ulong,VmciBufferMinSize,ZMQ_VMCI_BUFFER_MIN_SIZE) // bytes - SOCKOPT(ulong,VmciBufferMaxSize,ZMQ_VMCI_BUFFER_MAX_SIZE) // bytes - SOCKOPT(int,VmciConnectTimeout,ZMQ_VMCI_CONNECT_TIMEOUT) // milliseconds - }; -//+------------------------------------------------------------------+ -//| The option value is a string with predefined byte length | -//| | -//| If it is a NULL-terminated string without predefined length, | -//| The situation is tricky: we do not know the length of the option | -//| value beforehand, but the function does not return the correct | -//| one, either. So the only option is to guess. | -//| | -//| Here we adopt the solution of the Java binding. We just guess | -//| that the length of a NULL-terminated string option is less than | -//| 1024. So hopefully, it is the case. | -//+------------------------------------------------------------------+ -bool SocketOptions::getStringOption(int option,string &value,size_t length) - { - char buf[]; - ArrayResize(buf,(int)length); - bool res=getOption(option,buf,length); - if(res) - { - value=StringFromUtf8(buf); - } - ArrayFree(buf); - return res; - } -//+------------------------------------------------------------------+ -//| The ending means that the converted buffer contains the ending | -//| null. | -//+------------------------------------------------------------------+ -bool SocketOptions::setStringOption(int option,const string value,bool ending) - { - char buf[]; - StringToUtf8(value,buf,ending); - int len = ArraySize(buf); - bool res=setOption(option,buf,len); - ArrayFree(buf); - return res; - } -//+------------------------------------------------------------------+ diff --git a/Documents/Resources/ZeroMQ/Includes/Zmq.mqh b/Documents/Resources/ZeroMQ/Includes/Zmq.mqh deleted file mode 100644 index 173d11f..0000000 Binary files a/Documents/Resources/ZeroMQ/Includes/Zmq.mqh and /dev/null differ diff --git a/Documents/Resources/ZeroMQ/Includes/AtomicCounter.mqh b/Documents/Resources/ZeroMQ/Includes/Zmq/AtomicCounter.mqh similarity index 79% rename from Documents/Resources/ZeroMQ/Includes/AtomicCounter.mqh rename to Documents/Resources/ZeroMQ/Includes/Zmq/AtomicCounter.mqh index 096aca0..ebfe6cf 100644 --- a/Documents/Resources/ZeroMQ/Includes/AtomicCounter.mqh +++ b/Documents/Resources/ZeroMQ/Includes/Zmq/AtomicCounter.mqh @@ -24,7 +24,7 @@ #import "libzmq.dll" intptr_t zmq_atomic_counter_new(void); -void zmq_atomic_counter_set(intptr_t counter,int value); +void zmq_atomic_counter_set(intptr_t counter, int value); int zmq_atomic_counter_inc(intptr_t counter); int zmq_atomic_counter_dec(intptr_t counter); int zmq_atomic_counter_value(intptr_t counter); @@ -34,17 +34,17 @@ void zmq_atomic_counter_destroy(intptr_t &counter_p); //| Atomic counter utility | //+------------------------------------------------------------------+ class AtomicCounter - { +{ private: - intptr_t m_ref; + intptr_t m_ref; public: - AtomicCounter() {m_ref=zmq_atomic_counter_new();} - ~AtomicCounter() {zmq_atomic_counter_destroy(m_ref);} + AtomicCounter() { m_ref = zmq_atomic_counter_new(); } + ~AtomicCounter() { zmq_atomic_counter_destroy(m_ref); } - int increase() {return zmq_atomic_counter_inc(m_ref);} - int decrease() {return zmq_atomic_counter_dec(m_ref);} - int get() {return zmq_atomic_counter_value(m_ref);} - void set(int value) {zmq_atomic_counter_set(m_ref,value);} - }; + int increase() { return zmq_atomic_counter_inc(m_ref); } + int decrease() { return zmq_atomic_counter_dec(m_ref); } + int get() { return zmq_atomic_counter_value(m_ref); } + void set(int value) { zmq_atomic_counter_set(m_ref, value); } +}; //+------------------------------------------------------------------+ diff --git a/Documents/Resources/ZeroMQ/Includes/Context.mqh b/Documents/Resources/ZeroMQ/Includes/Zmq/Context.mqh similarity index 60% rename from Documents/Resources/ZeroMQ/Includes/Context.mqh rename to Documents/Resources/ZeroMQ/Includes/Zmq/Context.mqh index 1518230..5012648 100644 --- a/Documents/Resources/ZeroMQ/Includes/Context.mqh +++ b/Documents/Resources/ZeroMQ/Includes/Zmq/Context.mqh @@ -33,7 +33,7 @@ #define ZMQ_MAX_MSGSZ 5 //--- Default for new contexts -#define ZMQ_IO_THREADS_DFLT 1 +#define ZMQ_IO_THREADS_DFLT 1 #define ZMQ_MAX_SOCKETS_DFLT 1023 #define ZMQ_THREAD_PRIORITY_DFLT -1 #define ZMQ_THREAD_SCHED_POLICY_DFLT -1 @@ -42,23 +42,23 @@ intptr_t zmq_ctx_new(void); int zmq_ctx_term(intptr_t context); int zmq_ctx_shutdown(intptr_t context); -int zmq_ctx_set(intptr_t context,int option,int optval); -int zmq_ctx_get(intptr_t context,int option); +int zmq_ctx_set(intptr_t context, int option, int optval); +int zmq_ctx_get(intptr_t context, int option); #import -class ContextHandleManager: public HandleManager - { - intptr_t create() override - { - return zmq_ctx_new(); - } - void destroy(intptr_t handle) override - { - if(0!=zmq_ctx_term(handle)) +class ContextHandleManager : public HandleManager +{ + intptr_t create() override + { + return zmq_ctx_new(); + } + void destroy(intptr_t handle) override + { + if (0 != zmq_ctx_term(handle)) { - Debug("failed to terminate context"); + Debug("failed to terminate context"); } - } - }; + } +}; //+------------------------------------------------------------------+ //| Wraps a 0MZ context | //| | @@ -78,40 +78,75 @@ class ContextHandleManager: public HandleManager //| and in a manner not easily recognized by humans, for example: | //| "__3kewducdxhkd__" | //+------------------------------------------------------------------+ -class Context: public GlobalHandle - { +class Context : public GlobalHandle +{ protected: - int get(int option) {return zmq_ctx_get(m_ref,option);} - bool set(int option,int optval) {return 0==zmq_ctx_set(m_ref,option,optval);} + int get(int option) { return zmq_ctx_get(m_ref, option); } + bool set(int option, int optval) { return 0 == zmq_ctx_set(m_ref, option, optval); } public: + static intptr_t create() { return zmq_ctx_new(); } + static void destroy(intptr_t handle) + { + if (0 != zmq_ctx_term(handle)) + { + Debug("failed to terminate context"); + } + } - static intptr_t create() {return zmq_ctx_new();} - static void destroy(intptr_t handle) {if(0!=zmq_ctx_term(handle)) {Debug("failed to terminate context");}} + Context(string shared = NULL) : GlobalHandle(shared) {} - Context(string shared=NULL):GlobalHandle(shared) {} + bool shutdown() { return 0 == zmq_ctx_shutdown(m_ref); } - bool shutdown() {return 0==zmq_ctx_shutdown(m_ref);} + int getIoThreads() { return get(ZMQ_IO_THREADS); } + void setIoThreads(int value) + { + if (!set(ZMQ_IO_THREADS, value)) + { + Debug("failed to set ZMQ_IO_THREADS"); + } + } - int getIoThreads() {return get(ZMQ_IO_THREADS);} - void setIoThreads(int value) {if(!set(ZMQ_IO_THREADS,value)) {Debug("failed to set ZMQ_IO_THREADS");}} + int getMaxSockets() { return get(ZMQ_MAX_SOCKETS); } + void setMaxSockets(int value) + { + if (!set(ZMQ_MAX_SOCKETS, value)) + { + Debug("failed to set ZMQ_MAX_SOCKETS"); + } + } - int getMaxSockets() {return get(ZMQ_MAX_SOCKETS);} - void setMaxSockets(int value) {if(!set(ZMQ_MAX_SOCKETS,value)) {Debug("failed to set ZMQ_MAX_SOCKETS");}} + int getMaxMessageSize() { return get(ZMQ_MAX_MSGSZ); } + void setMaxMessageSize(int value) + { + if (!set(ZMQ_MAX_MSGSZ, value)) + { + Debug("failed to set ZMQ_MAX_MSGSZ"); + } + } - int getMaxMessageSize() {return get(ZMQ_MAX_MSGSZ);} - void setMaxMessageSize(int value) {if(!set(ZMQ_MAX_MSGSZ,value)) {Debug("failed to set ZMQ_MAX_MSGSZ");}} + int getSocketLimit() { return get(ZMQ_SOCKET_LIMIT); } - int getSocketLimit() {return get(ZMQ_SOCKET_LIMIT);} + int getIpv6Options() { return get(ZMQ_IPV6); } + void setIpv6Options(int value) + { + if (!set(ZMQ_IPV6, value)) + { + Debug("failed to set ZMQ_IPV6"); + } + } - int getIpv6Options() {return get(ZMQ_IPV6);} - void setIpv6Options(int value) {if(!set(ZMQ_IPV6,value)) {Debug("failed to set ZMQ_IPV6");}} + bool isBlocky() { return 1 == get(ZMQ_BLOCKY); } + void setBlocky(bool value) + { + if (!set(ZMQ_BLOCKY, value ? 1 : 0)) + { + Debug("failed to set ZMQ_BLOCKY"); + } + } - bool isBlocky() {return 1==get(ZMQ_BLOCKY);} - void setBlocky(bool value) {if(!set(ZMQ_BLOCKY,value?1:0)) {Debug("failed to set ZMQ_BLOCKY");}} - - //--- Following options is not supported on windows - void setSchedulingPolicy(int value) {/*ZMQ_THREAD_SCHED_POLICY*/} - void setThreadPriority(int value) {/*ZMQ_THREAD_PRIORITY*/} - }; + //--- Following options is not supported on windows + void setSchedulingPolicy(int value) { /*ZMQ_THREAD_SCHED_POLICY*/ } + void setThreadPriority(int value) { /*ZMQ_THREAD_PRIORITY*/ } +}; //+------------------------------------------------------------------+ diff --git a/Documents/Resources/ZeroMQ/Includes/Errno.mqh b/Documents/Resources/ZeroMQ/Includes/Zmq/Errno.mqh similarity index 62% rename from Documents/Resources/ZeroMQ/Includes/Errno.mqh rename to Documents/Resources/ZeroMQ/Includes/Zmq/Errno.mqh index 2be9f3b..76053a4 100644 --- a/Documents/Resources/ZeroMQ/Includes/Errno.mqh +++ b/Documents/Resources/ZeroMQ/Includes/Zmq/Errno.mqh @@ -22,75 +22,75 @@ // Following error codes come from Microsoft CRT header errno.h // Error codes -#define EPERM 1 -#define ENOENT 2 -#define ESRCH 3 -#define EINTR 4 -#define EIO 5 -#define ENXIO 6 -#define E2BIG 7 -#define ENOEXEC 8 -#define EBADF 9 -#define ECHILD 10 -#define EAGAIN 11 -#define ENOMEM 12 -#define EACCES 13 -#define EFAULT 14 -#define EBUSY 16 -#define EEXIST 17 -#define EXDEV 18 -#define ENODEV 19 -#define ENOTDIR 20 -#define EISDIR 21 -#define ENFILE 23 -#define EMFILE 24 -#define ENOTTY 25 -#define EFBIG 27 -#define ENOSPC 28 -#define ESPIPE 29 -#define EROFS 30 -#define EMLINK 31 -#define EPIPE 32 -#define EDOM 33 -#define EDEADLK 36 -#define ENAMETOOLONG 38 -#define ENOLCK 39 -#define ENOSYS 40 -#define ENOTEMPTY 41 +#define EPERM 1 +#define ENOENT 2 +#define ESRCH 3 +#define EINTR 4 +#define EIO 5 +#define ENXIO 6 +#define E2BIG 7 +#define ENOEXEC 8 +#define EBADF 9 +#define ECHILD 10 +#define EAGAIN 11 +#define ENOMEM 12 +#define EACCES 13 +#define EFAULT 14 +#define EBUSY 16 +#define EEXIST 17 +#define EXDEV 18 +#define ENODEV 19 +#define ENOTDIR 20 +#define EISDIR 21 +#define ENFILE 23 +#define EMFILE 24 +#define ENOTTY 25 +#define EFBIG 27 +#define ENOSPC 28 +#define ESPIPE 29 +#define EROFS 30 +#define EMLINK 31 +#define EPIPE 32 +#define EDOM 33 +#define EDEADLK 36 +#define ENAMETOOLONG 38 +#define ENOLCK 39 +#define ENOSYS 40 +#define ENOTEMPTY 41 // Error codes used in the Secure CRT functions -#define EINVAL 22 -#define ERANGE 34 -#define EILSEQ 42 -#define STRUNCATE 80 +#define EINVAL 22 +#define ERANGE 34 +#define EILSEQ 42 +#define STRUNCATE 80 // Support EDEADLOCK for compatibility with older Microsoft C versions -#define EDEADLOCK EDEADLK +#define EDEADLOCK EDEADLK // POSIX Supplement -#define EALREADY 103 -#define EBADMSG 104 -#define ECANCELED 105 -#define EDESTADDRREQ 109 -#define EIDRM 111 -#define EISCONN 113 -#define ELOOP 114 -#define ENODATA 120 -#define ENOLINK 121 -#define ENOMSG 122 -#define ENOPROTOOPT 123 -#define ENOSR 124 -#define ENOSTR 125 +#define EALREADY 103 +#define EBADMSG 104 +#define ECANCELED 105 +#define EDESTADDRREQ 109 +#define EIDRM 111 +#define EISCONN 113 +#define ELOOP 114 +#define ENODATA 120 +#define ENOLINK 121 +#define ENOMSG 122 +#define ENOPROTOOPT 123 +#define ENOSR 124 +#define ENOSTR 125 #define ENOTRECOVERABLE 127 -#define EOPNOTSUPP 130 -#define EOTHER 131 -#define EOVERFLOW 132 -#define EOWNERDEAD 133 -#define EPROTO 134 -#define EPROTOTYPE 136 -#define ETIME 137 -#define ETXTBSY 139 -#define EWOULDBLOCK 140 +#define EOPNOTSUPP 130 +#define EOTHER 131 +#define EOVERFLOW 132 +#define EOWNERDEAD 133 +#define EPROTO 134 +#define EPROTOTYPE 136 +#define ETIME 137 +#define ETXTBSY 139 +#define EWOULDBLOCK 140 // Following error codes come from zmq.h // 0MQ errors diff --git a/Documents/Resources/ZeroMQ/Includes/Zmq/Socket.mqh b/Documents/Resources/ZeroMQ/Includes/Zmq/Socket.mqh new file mode 100644 index 0000000..71cadb9 --- /dev/null +++ b/Documents/Resources/ZeroMQ/Includes/Zmq/Socket.mqh @@ -0,0 +1,299 @@ +//+------------------------------------------------------------------+ +//| Module: Socket.mqh | +//| This file is part of the mql-zmq project: | +//| https://github.com/dingmaotu/mql-zmq | +//| | +//| Copyright 2016-2017 Li Ding | +//| | +//| Licensed under the Apache License, Version 2.0 (the "License"); | +//| you may not use this file except in compliance with the License. | +//| You may obtain a copy of the License at | +//| | +//| http://www.apache.org/licenses/LICENSE-2.0 | +//| | +//| Unless required by applicable law or agreed to in writing, | +//| software distributed under the License is distributed on an | +//| "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, | +//| either express or implied. | +//| See the License for the specific language governing permissions | +//| and limitations under the License. | +//+------------------------------------------------------------------+ +#property strict + +#include +#include +#include "Context.mqh" +#include "SocketOptions.mqh" +#include "ZmqMsg.mqh" + +//--- Socket types +#define ZMQ_PAIR 0 +#define ZMQ_PUB 1 +#define ZMQ_SUB 2 +#define ZMQ_REQ 3 +#define ZMQ_REP 4 +#define ZMQ_DEALER 5 +#define ZMQ_ROUTER 6 +#define ZMQ_PULL 7 +#define ZMQ_PUSH 8 +#define ZMQ_XPUB 9 +#define ZMQ_XSUB 10 +#define ZMQ_STREAM 11 + +//--- Message options +#define ZMQ_MORE 1 +#define ZMQ_SRCFD 2 // Deprecated +#define ZMQ_SHARED 3 + +//--- Send/recv options +#define ZMQ_DONTWAIT 1 +#define ZMQ_SNDMORE 2 + +//--- Socket transport events (TCP, IPC and TIPC only) +#define ZMQ_EVENT_CONNECTED 0x0001 +#define ZMQ_EVENT_CONNECT_DELAYED 0x0002 +#define ZMQ_EVENT_CONNECT_RETRIED 0x0004 +#define ZMQ_EVENT_LISTENING 0x0008 +#define ZMQ_EVENT_BIND_FAILED 0x0010 +#define ZMQ_EVENT_ACCEPTED 0x0020 +#define ZMQ_EVENT_ACCEPT_FAILED 0x0040 +#define ZMQ_EVENT_CLOSED 0x0080 +#define ZMQ_EVENT_CLOSE_FAILED 0x0100 +#define ZMQ_EVENT_DISCONNECTED 0x0200 +#define ZMQ_EVENT_MONITOR_STOPPED 0x0400 +#define ZMQ_EVENT_ALL 0xFFFF + +//--- I/O multiplexing +#define ZMQ_POLLIN 1 +#define ZMQ_POLLOUT 2 +// We only use 0MQ sockets on Windows +// So POLLERR and POLLPRI is of no use +#define ZMQ_POLLERR 4 +#define ZMQ_POLLPRI 8 + +#define ZMQ_POLLITEMS_DFLT 16 +//--- fd is SOCKET on Win32, which is defined as UINT_PTR +struct PollItem +{ + intptr_t socket; + uintptr_t fd; + short events; + short revents; +#ifdef __X64__ + //--- note here that if the program runs on 64bit runtime, we need to pad the + //--- struct to align to 8 bytes + //--- thanks https://github.com/feng-ye for the solution to https://github.com/dingmaotu/mql-zmq/issues/14 + int __unused; +#endif + + bool hasInput() const { return (revents & ZMQ_POLLIN) != 0; } + bool hasOutput() const { return (revents & ZMQ_POLLOUT) != 0; } +}; +#import "libzmq.dll" +//+------------------------------------------------------------------+ +//| Sockets | +//+------------------------------------------------------------------+ +intptr_t zmq_socket(intptr_t context, int type); +int zmq_close(intptr_t s); +int zmq_bind(intptr_t s, const char &addr[]); +int zmq_connect(intptr_t s, const char &addr[]); +int zmq_unbind(intptr_t s, const char &addr[]); +int zmq_disconnect(intptr_t s, const char &addr[]); +int zmq_send(intptr_t s, const uchar &buf[], size_t len, int flags); +int zmq_send_const(intptr_t s, const uchar &buf[], size_t len, int flags); +int zmq_recv(intptr_t s, uchar &buf[], size_t len, int flags); +int zmq_socket_monitor(intptr_t s, const char &addr[], int events); +//+------------------------------------------------------------------+ +//| Message | +//+------------------------------------------------------------------+ +int zmq_msg_send(zmq_msg_t &msg, intptr_t s, int flags); +int zmq_msg_recv(zmq_msg_t &msg, intptr_t s, int flags); +//+------------------------------------------------------------------+ +//| I/O multiplexing | +//+------------------------------------------------------------------+ +int zmq_poll(PollItem &items[], int nitems, long timeout); +//+------------------------------------------------------------------+ +//| Message proxying | +//+------------------------------------------------------------------+ +int zmq_proxy(intptr_t frontend_ref, intptr_t backend_ref, intptr_t capture_ref); +int zmq_proxy_steerable(intptr_t frontend_ref, intptr_t backend_ref, intptr_t capture_ref, intptr_t control_ref); +#import +//+------------------------------------------------------------------+ +//| Wraps a 0MQ socket | +//+------------------------------------------------------------------+ +class Socket : public SocketOptions +{ +public: + Socket(const Context &ctx, int type) : SocketOptions(zmq_socket(ctx.ref(), type)) {} + virtual ~Socket() + { + if (0 != zmq_close(m_ref)) + { + Debug(StringFormat("Failed to close socket 0x%0X", m_ref)); + } + } + + // for better cooperation between objects + intptr_t ref() const { return m_ref; } + + bool valid() const { return m_ref != 0; } + + //--- see Zmq::error() if any of the following command failed + //--- connection management + bool bind(string addr); + bool unbind(string addr); + bool connect(string addr); + bool disconnect(string addr); + + //--- send raw bytes + bool send(const uchar &buf[], bool nowait = false) { return -1 != zmq_send(m_ref, buf, ArraySize(buf), nowait ? ZMQ_DONTWAIT : 0); } + bool sendConst(const uchar &buf[], bool nowait = false) { return -1 != zmq_send_const(m_ref, buf, ArraySize(buf), nowait ? ZMQ_DONTWAIT : 0); } + + //--- send ZmqMsg + bool send(ZmqMsg &msg, bool nowait = false) { return -1 != zmq_msg_send(msg, m_ref, nowait ? ZMQ_DONTWAIT : 0); } + //--- send string + bool send(string msg, bool nowait = false) + { + ZmqMsg m(msg); + return send(m, nowait); + } + //--- send empty + bool send(bool nowait = false) + { + ZmqMsg m; + return send(m, nowait); + } + + //--- same as above 5 but for multipart messages + bool sendMore(const uchar &buf[], bool nowait = false); + bool sendConstMore(const uchar &buf[], bool nowait = false); + bool sendMore(ZmqMsg &msg, bool nowait = false) + { + int flags = ZMQ_SNDMORE; + if (nowait) + flags |= ZMQ_DONTWAIT; + return -1 != zmq_msg_send(msg, m_ref, flags); + } + bool sendMore(string msg, bool nowait = false) + { + ZmqMsg m(msg); + return sendMore(m, nowait); + } + bool sendMore(bool nowait = false) + { + ZmqMsg m; + return sendMore(m, nowait); + } + + //--- receive packets + bool recv(uchar &buf[], bool nowait = false) { return -1 != zmq_recv(m_ref, buf, ArraySize(buf), nowait ? ZMQ_DONTWAIT : 0); } + bool recv(ZmqMsg &msg, bool nowait = false) { return -1 != zmq_msg_recv(msg, m_ref, nowait ? ZMQ_DONTWAIT : 0); } + + //--- monitor socket events + bool monitor(string addr, int events); + + //--- proxy + static bool proxy(Socket *frontend, Socket *backend, Socket *capture); + static bool proxySteerable(Socket *frontend, Socket *backend, Socket *capture, Socket *control); + + //--- poll + static int poll(PollItem &arr[], long timeout); + + //--- fill a poll item for this socket + void fillPollItem(PollItem &item, short events); +}; +//+------------------------------------------------------------------+ +//| | +//+------------------------------------------------------------------+ +bool Socket::bind(string addr) +{ + char arr[]; + StringToUtf8(addr, arr); + bool res = (0 == zmq_bind(m_ref, arr)); + ArrayFree(arr); + return res; +} +//+------------------------------------------------------------------+ +//| | +//+------------------------------------------------------------------+ +bool Socket::unbind(string addr) +{ + char arr[]; + StringToUtf8(addr, arr); + bool res = (0 == zmq_unbind(m_ref, arr)); + ArrayFree(arr); + return res; +} +//+------------------------------------------------------------------+ +//| | +//+------------------------------------------------------------------+ +bool Socket::connect(string addr) +{ + char arr[]; + StringToUtf8(addr, arr); + bool res = (0 == zmq_connect(m_ref, arr)); + ArrayFree(arr); + return res; +} +//+------------------------------------------------------------------+ +//| | +//+------------------------------------------------------------------+ +bool Socket::disconnect(string addr) +{ + char arr[]; + StringToUtf8(addr, arr); + bool res = (0 == zmq_disconnect(m_ref, arr)); + ArrayFree(arr); + return res; +} +//+------------------------------------------------------------------+ +//| | +//+------------------------------------------------------------------+ +bool Socket::monitor(string addr, int events) +{ + char str[]; + StringToUtf8(addr, str); + bool res = (0 == zmq_socket_monitor(m_ref, str, events)); + ArrayFree(str); + return res; +} +//+------------------------------------------------------------------+ +//| | +//+------------------------------------------------------------------+ +bool Socket::proxy(Socket *frontend, Socket *backend, Socket *capture) +{ + intptr_t frontend_ref = CheckPointer(frontend) == POINTER_DYNAMIC ? frontend.ref() : 0; + intptr_t backend_ref = CheckPointer(backend) == POINTER_DYNAMIC ? backend.ref() : 0; + intptr_t capture_ref = CheckPointer(capture) == POINTER_DYNAMIC ? capture.ref() : 0; + return 0 == zmq_proxy(frontend_ref, backend_ref, capture_ref); +} +//+------------------------------------------------------------------+ +//| | +//+------------------------------------------------------------------+ +bool Socket::proxySteerable(Socket *frontend, Socket *backend, Socket *capture, Socket *control) +{ + intptr_t frontend_ref = CheckPointer(frontend) == POINTER_DYNAMIC ? frontend.ref() : 0; + intptr_t backend_ref = CheckPointer(backend) == POINTER_DYNAMIC ? backend.ref() : 0; + intptr_t capture_ref = CheckPointer(capture) == POINTER_DYNAMIC ? capture.ref() : 0; + intptr_t control_ref = CheckPointer(control) == POINTER_DYNAMIC ? control.ref() : 0; + return 0 == zmq_proxy_steerable(frontend_ref, backend_ref, capture_ref, control_ref); +} +//+------------------------------------------------------------------+ +//| poll for events. timeout is milliseconds (-1 for indefinite wait | +//| and 0 for immediate return) | +//+------------------------------------------------------------------+ +int Socket::poll(PollItem &arr[], long timeout) +{ + return zmq_poll(arr, ArraySize(arr), timeout); +} +//+------------------------------------------------------------------+ +//| fill a poll item for this socket | +//+------------------------------------------------------------------+ +void Socket::fillPollItem(PollItem &item, short events) +{ + item.socket = m_ref; + item.fd = 0; + item.events = events; + item.revents = 0; +} +//+------------------------------------------------------------------+ diff --git a/Documents/Resources/ZeroMQ/Includes/Zmq/SocketOptions.mqh b/Documents/Resources/ZeroMQ/Includes/Zmq/SocketOptions.mqh new file mode 100644 index 0000000..61d21a6 --- /dev/null +++ b/Documents/Resources/ZeroMQ/Includes/Zmq/SocketOptions.mqh @@ -0,0 +1,383 @@ +//+------------------------------------------------------------------+ +//| Module: SocketOptions.mqh | +//| This file is part of the mql-zmq project: | +//| https://github.com/dingmaotu/mql-zmq | +//| | +//| Copyright 2016-2017 Li Ding | +//| | +//| Licensed under the Apache License, Version 2.0 (the "License"); | +//| you may not use this file except in compliance with the License. | +//| You may obtain a copy of the License at | +//| | +//| http://www.apache.org/licenses/LICENSE-2.0 | +//| | +//| Unless required by applicable law or agreed to in writing, | +//| software distributed under the License is distributed on an | +//| "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, | +//| either express or implied. | +//| See the License for the specific language governing permissions | +//| and limitations under the License. | +//+------------------------------------------------------------------+ +#property strict + +#include + +#import "libzmq.dll" +// We can overload the same function for different data types +// as in the C level the optval paramter is just a pointer +#define SOCKOPT_OVERLOAD_ARRAY(TYPE) \ + int zmq_setsockopt(intptr_t s, int option, const TYPE &optval[], \ + size_t optvallen); \ + int zmq_getsockopt(intptr_t s, int option, TYPE &optval[], \ + size_t &optvallen); + +#define SOCKOPT_OVERLOAD(TYPE) \ + int zmq_setsockopt(intptr_t s, int option, const TYPE &optval, \ + size_t optvallen); \ + int zmq_getsockopt(intptr_t s, int option, TYPE &optval, \ + size_t &optvallen); + +SOCKOPT_OVERLOAD_ARRAY(uchar) +SOCKOPT_OVERLOAD(long) +SOCKOPT_OVERLOAD(ulong) +SOCKOPT_OVERLOAD(int) +SOCKOPT_OVERLOAD(uint) +#import + +// Socket options +#define ZMQ_AFFINITY 4 +#define ZMQ_IDENTITY 5 +#define ZMQ_SUBSCRIBE 6 +#define ZMQ_UNSUBSCRIBE 7 +#define ZMQ_RATE 8 +#define ZMQ_RECOVERY_IVL 9 +#define ZMQ_SNDBUF 11 +#define ZMQ_RCVBUF 12 +#define ZMQ_RCVMORE 13 +#define ZMQ_FD 14 +#define ZMQ_EVENTS 15 +#define ZMQ_TYPE 16 +#define ZMQ_LINGER 17 +#define ZMQ_RECONNECT_IVL 18 +#define ZMQ_BACKLOG 19 +#define ZMQ_RECONNECT_IVL_MAX 21 +#define ZMQ_MAXMSGSIZE 22 +#define ZMQ_SNDHWM 23 +#define ZMQ_RCVHWM 24 +#define ZMQ_MULTICAST_HOPS 25 +#define ZMQ_RCVTIMEO 27 +#define ZMQ_SNDTIMEO 28 +#define ZMQ_LAST_ENDPOINT 32 +#define ZMQ_ROUTER_MANDATORY 33 +#define ZMQ_TCP_KEEPALIVE 34 +#define ZMQ_TCP_KEEPALIVE_CNT 35 +#define ZMQ_TCP_KEEPALIVE_IDLE 36 +#define ZMQ_TCP_KEEPALIVE_INTVL 37 +#define ZMQ_IMMEDIATE 39 +#define ZMQ_XPUB_VERBOSE 40 +#define ZMQ_ROUTER_RAW 41 +#define ZMQ_IPV6 42 +#define ZMQ_MECHANISM 43 +#define ZMQ_PLAIN_SERVER 44 +#define ZMQ_PLAIN_USERNAME 45 +#define ZMQ_PLAIN_PASSWORD 46 +#define ZMQ_CURVE_SERVER 47 +#define ZMQ_CURVE_PUBLICKEY 48 +#define ZMQ_CURVE_SECRETKEY 49 +#define ZMQ_CURVE_SERVERKEY 50 +#define ZMQ_PROBE_ROUTER 51 +#define ZMQ_REQ_CORRELATE 52 +#define ZMQ_REQ_RELAXED 53 +#define ZMQ_CONFLATE 54 +#define ZMQ_ZAP_DOMAIN 55 +#define ZMQ_ROUTER_HANDOVER 56 +#define ZMQ_TOS 57 +#define ZMQ_CONNECT_RID 61 +#define ZMQ_GSSAPI_SERVER 62 +#define ZMQ_GSSAPI_PRINCIPAL 63 +#define ZMQ_GSSAPI_SERVICE_PRINCIPAL 64 +#define ZMQ_GSSAPI_PLAINTEXT 65 +#define ZMQ_HANDSHAKE_IVL 66 +#define ZMQ_SOCKS_PROXY 68 +#define ZMQ_XPUB_NODROP 69 +#define ZMQ_BLOCKY 70 +#define ZMQ_XPUB_MANUAL 71 +#define ZMQ_XPUB_WELCOME_MSG 72 +#define ZMQ_STREAM_NOTIFY 73 +#define ZMQ_INVERT_MATCHING 74 +#define ZMQ_HEARTBEAT_IVL 75 +#define ZMQ_HEARTBEAT_TTL 76 +#define ZMQ_HEARTBEAT_TIMEOUT 77 +#define ZMQ_XPUB_VERBOSER 78 +#define ZMQ_CONNECT_TIMEOUT 79 +#define ZMQ_TCP_MAXRT 80 +#define ZMQ_THREAD_SAFE 81 +#define ZMQ_MULTICAST_MAXTPDU 84 +#define ZMQ_VMCI_BUFFER_SIZE 85 +#define ZMQ_VMCI_BUFFER_MIN_SIZE 86 +#define ZMQ_VMCI_BUFFER_MAX_SIZE 87 +#define ZMQ_VMCI_CONNECT_TIMEOUT 88 +#define ZMQ_USE_FD 89 +//+------------------------------------------------------------------+ +//| A dedicated class to get/set socket options | +//+------------------------------------------------------------------+ +class SocketOptions +{ +protected: + intptr_t m_ref; + +#define SOCKOPT_WRAP_ARRAY(TYPE) \ + bool setOption(int option, const TYPE &value[], size_t len) { return 0 == zmq_setsockopt(m_ref, option, value, len); } \ + bool getOption(int option, TYPE &value[], size_t &len) { return 0 == zmq_getsockopt(m_ref, option, value, len); } + +#define SOCKOPT_WRAP(TYPE) \ + bool setOption(int option, TYPE value) { return 0 == zmq_setsockopt(m_ref, option, value, sizeof(TYPE)); } \ + bool getOption(int option, TYPE &value) \ + { \ + size_t s = sizeof(TYPE); \ + return 0 == zmq_getsockopt(m_ref, option, value, s); \ + } + + SOCKOPT_WRAP_ARRAY(uchar) + SOCKOPT_WRAP(int) + SOCKOPT_WRAP(uint) + SOCKOPT_WRAP(long) + SOCKOPT_WRAP(ulong) + + bool setStringOption(int option, string value, bool ending = true); + bool getStringOption(int option, string &value, size_t length = 1024); + SocketOptions(intptr_t ref) : m_ref(ref) {} + +public: + //--- option templates + //--- various integer options +#define SOCKOPT_GET(TYPE, NAME, MACRO) \ + bool get##NAME(TYPE &value) { return getOption(MACRO, value); } +#define SOCKOPT_SET(TYPE, NAME, MACRO) \ + bool set##NAME(TYPE value) { return setOption(MACRO, value); } +#define SOCKOPT(TYPE, NAME, MACRO) \ + SOCKOPT_GET(TYPE, NAME, MACRO) \ + SOCKOPT_SET(TYPE, NAME, MACRO) + + //--- boolean options +#define SOCKOPT_GET_BOOL(NAME, MACRO) \ + bool is##NAME(bool &value) \ + { \ + int v; \ + bool res = getOption(MACRO, v); \ + value = (v == 1); \ + return res; \ + } +#define SOCKOPT_SET_BOOL(NAME, MACRO) \ + bool set##NAME(bool value) { return setOption(MACRO, value ? 1 : 0); } +#define SOCKOPT_BOOL(NAME, MACRO) \ + SOCKOPT_GET_BOOL(NAME, MACRO) \ + SOCKOPT_SET_BOOL(NAME, MACRO) + + //--- null-terminated string options +#define SOCKOPT_GET_NTSTR(NAME, MACRO) \ + bool get##NAME(string &value) { return getStringOption(MACRO, value); } +#define SOCKOPT_SET_NTSTR(NAME, MACRO) \ + bool set##NAME(string value) { return setStringOption(MACRO, value); } +#define SOCKOPT_NTSTR(NAME, MACRO) \ + SOCKOPT_GET_NTSTR(NAME, MACRO) \ + SOCKOPT_SET_NTSTR(NAME, MACRO) + + //--- bytes array or string converted options +#define SOCKOPT_SET_BYTES(OptionName, Macro) \ + bool set##OptionName(const uchar &value[]) { return setOption(Macro, value, (size_t)ArraySize(value)); } \ + bool set##OptionName(string value) { return setStringOption(Macro, value, false); } +#define SOCKOPT_GET_BYTES(OptionName, Macro, InitSize) \ + bool get##OptionName(uchar &value[]) \ + { \ + size_t len = (size_t)InitSize; \ + ArrayResize(value, (int)len); \ + bool res = getOption(Macro, value, len); \ + if (res) \ + { \ + ArrayResize(value, (int)len); \ + } \ + return res; \ + } \ + bool get##OptionName(string &value) { return getStringOption(Macro, value, InitSize); } +#define SOCKOPT_BYTES(OptionName, Macro, InitSize) \ + SOCKOPT_SET_BYTES(OptionName, Macro) \ + SOCKOPT_GET_BYTES(OptionName, Macro, InitSize) + + //--- for curve key + //--- NOTE that the length of the key array must be 32. + //--- since some versions of mt4 and newer versions of mt5 will report error + //--- when the length of the array is specified, so the length specification is removed +#define SOCKOPT_CURVE_KEY(KeyType, Macro) \ + bool getCurve##KeyType##Key(uchar &key[]) \ + { \ + size_t len = 32; \ + return getOption(Macro, key, len); \ + } \ + bool getCurve##KeyType##Key(string &key) { return getStringOption(Macro, key, 41); } \ + bool setCurve##KeyType##Key(const uchar &key[]) { return setOption(Macro, key, 32); } \ + bool setCurve##KeyType##Key(string key) { return setStringOption(Macro, key); } + + SOCKOPT_GET(int, Type, ZMQ_TYPE) + SOCKOPT(ulong, Affinity, ZMQ_AFFINITY) // 64bit bitmask + SOCKOPT(int, BackLog, ZMQ_BACKLOG) // number of connections + SOCKOPT(int, Timeout, ZMQ_CONNECT_TIMEOUT) // milliseconds + SOCKOPT_GET_BOOL(ThreadSafe, ZMQ_THREAD_SAFE) + + SOCKOPT_SET_BOOL(Conflate, ZMQ_CONFLATE) // only for ZMQ_PULL, ZMQ_PUSH, ZMQ_SUB, ZMQ_PUB, ZMQ_DEALER types + + SOCKOPT_GET(int, Events, ZMQ_EVENTS); // bitmask of ZMQ_POLLIN, ZMQ_POLLOUT + + SOCKOPT_GET(uintptr_t, FileDescriptor, ZMQ_FD) + + SOCKOPT_GET(int, Mechanism, ZMQ_MECHANISM) // current security mechanism + + //--- plain + SOCKOPT_NTSTR(PlainUsername, ZMQ_PLAIN_USERNAME) + SOCKOPT_NTSTR(PlainPassword, ZMQ_PLAIN_PASSWORD) + SOCKOPT_BOOL(PlainServer, ZMQ_PLAIN_SERVER) + + //--- gssapi: this is not supported in this binding. Following methods will FAIL if you invoke them + SOCKOPT_BOOL(GssApiPlainText, ZMQ_GSSAPI_PLAINTEXT) + SOCKOPT_BOOL(GssApiServer, ZMQ_GSSAPI_SERVER) + SOCKOPT_NTSTR(GssApiPrincipal, ZMQ_GSSAPI_PRINCIPAL) + SOCKOPT_NTSTR(GssApiServicePrincipal, ZMQ_GSSAPI_SERVICE_PRINCIPAL) + + //--- curve + SOCKOPT_CURVE_KEY(Public, ZMQ_CURVE_PUBLICKEY) + SOCKOPT_CURVE_KEY(Secret, ZMQ_CURVE_SECRETKEY) + SOCKOPT_CURVE_KEY(Server, ZMQ_CURVE_SERVERKEY) + + SOCKOPT_SET_BOOL(CurveServer, ZMQ_CURVE_SERVER) + + SOCKOPT_GET_NTSTR(LastEndpoint, ZMQ_LAST_ENDPOINT) + + SOCKOPT(int, HandshakeInterval, ZMQ_HANDSHAKE_IVL) // milliseconds + SOCKOPT_SET(int, HeartbeatInterval, ZMQ_HEARTBEAT_IVL) // milliseconds + SOCKOPT_SET(int, HeartbeatTimeout, ZMQ_HEARTBEAT_TIMEOUT) // milliseconds + SOCKOPT_SET(int, HeartbeatTTL, ZMQ_HEARTBEAT_TTL) // milliseconds + + SOCKOPT_BOOL(Immediate, ZMQ_IMMEDIATE) + SOCKOPT_BOOL(Ipv6, ZMQ_IPV6) //--- ZMQ_IPV4ONLY is deprecated, use this instead + SOCKOPT(int, Linger, ZMQ_LINGER) // milliseconds + SOCKOPT(long, MaxMessageSize, ZMQ_MAXMSGSIZE) + + //--- multicast + SOCKOPT(int, MulticastHops, ZMQ_MULTICAST_HOPS) // hops + SOCKOPT(int, MulticastMaxTPDU, ZMQ_MULTICAST_MAXTPDU) // bytes + SOCKOPT(int, MulticastRate, ZMQ_RATE) // kilobits per second + SOCKOPT(int, RecoveryInterval, ZMQ_RECOVERY_IVL) // multicast recovery interval + + //--- there is a problem here: FileDescriptor should be SOCKET type on Windows, + //--- while in the zmq doc it is a int. Possible error in the doc + SOCKOPT(uintptr_t, UseFileDescriptor, ZMQ_USE_FD) + + SOCKOPT_SET_BOOL(ProbeRouter, ZMQ_PROBE_ROUTER) // only for ZMQ_ROUTER, ZMQ_DEALER, ZMQ_REQ + + SOCKOPT(int, ReceiveBuffer, ZMQ_RCVBUF) // bytes + SOCKOPT(int, ReceiveHighWaterMark, ZMQ_RCVHWM) // messages + SOCKOPT(int, ReceiveTimeout, ZMQ_RCVTIMEO) // milliseconds + SOCKOPT(int, SendBuffer, ZMQ_SNDBUF) // bytes + SOCKOPT(int, SendHighWaterMark, ZMQ_SNDHWM) // messages + SOCKOPT(int, SendTimeout, ZMQ_SNDTIMEO) + + SOCKOPT_GET_BOOL(ReceiveMore, ZMQ_RCVMORE) + + SOCKOPT(int, ReconnectInterval, ZMQ_RECONNECT_IVL) // milliseconds + SOCKOPT(int, ReconnectIntervalMax, ZMQ_RECONNECT_IVL_MAX) // milliseconds + + //--- only for ZMQ_REQ + SOCKOPT_SET_BOOL(RequestCorrelated, ZMQ_REQ_CORRELATE) + SOCKOPT_SET_BOOL(RequestRelaxed, ZMQ_REQ_RELAXED) + + //--- only for ZMQ_SUB + SOCKOPT_SET_BYTES(Subscribe, ZMQ_SUBSCRIBE) + SOCKOPT_SET_BYTES(Unsubscribe, ZMQ_UNSUBSCRIBE) + + //--- convenience methods + bool subscribe(string channel) { return setSubscribe(channel); } + bool unsubscribe(string channel) { return setUnsubscribe(channel); } + + //--- only for ZMQ_XSUB + SOCKOPT_BOOL(XpubVerbose, ZMQ_XPUB_VERBOSE) + SOCKOPT_BOOL(XpubVerboser, ZMQ_XPUB_VERBOSER) + SOCKOPT_BOOL(XpubManual, ZMQ_XPUB_MANUAL) + SOCKOPT_BOOL(XpubNoDrop, ZMQ_XPUB_NODROP) // also for ZMQ_PUB + SOCKOPT_SET_BYTES(XpubWelcomeMessage, ZMQ_XPUB_WELCOME_MSG) + + SOCKOPT_BOOL(InvertMatching, ZMQ_INVERT_MATCHING) //--- only for ZMQ_PUB, ZMQ_XPUB, ZMQ_SUB + + //--- only for ZMQ_ROUTER + SOCKOPT_SET_BOOL(RouterHandover, ZMQ_ROUTER_HANDOVER) + SOCKOPT_SET_BOOL(RouterMandatory, ZMQ_ROUTER_MANDATORY) + SOCKOPT_SET_BOOL(RouterRaw, ZMQ_ROUTER_RAW) + + //--- only for ZMQ_STREAM + SOCKOPT_SET_BOOL(StreamNotify, ZMQ_STREAM_NOTIFY) + + //--- only for ZMQ_ROUTER, ZMQ_STREAM + SOCKOPT_SET_BYTES(ConnectRid, ZMQ_CONNECT_RID) + + //--- only for ZMQ_REP, ZMQ_REQ, ZMQ_ROUTER, ZMQ_DEALER + SOCKOPT_BYTES(Identity, ZMQ_IDENTITY, 255) + + //--- tcp + SOCKOPT(int, TcpKeepAlive, ZMQ_TCP_KEEPALIVE) + SOCKOPT(int, TcpKeepAliveCount, ZMQ_TCP_KEEPALIVE_CNT) + SOCKOPT(int, TcpKeepAliveIdle, ZMQ_TCP_KEEPALIVE_IDLE) + SOCKOPT(int, TcpKeepAliveInterval, ZMQ_TCP_KEEPALIVE_INTVL) + SOCKOPT(int, TcpMaxRetransmitTimeout, ZMQ_TCP_MAXRT) + + SOCKOPT(int, TypeOfService, ZMQ_TOS) // IP_TOS + + //--- ZMQ_TCP_ACCEPT_FILTER + //--- ZMQ_IPC_FILTER_GID + //--- ZMQ_IPC_FILTER_PID + //--- ZMQ_IPC_FILTER_UID + //--- are deprecated in favor of ZAP API and ip address whitelisting/blacklisting + SOCKOPT_NTSTR(ZapDomain, ZMQ_ZAP_DOMAIN) + + //--- only for vmci transport + SOCKOPT(ulong, VmciBufferSize, ZMQ_VMCI_BUFFER_SIZE) // bytes + SOCKOPT(ulong, VmciBufferMinSize, ZMQ_VMCI_BUFFER_MIN_SIZE) // bytes + SOCKOPT(ulong, VmciBufferMaxSize, ZMQ_VMCI_BUFFER_MAX_SIZE) // bytes + SOCKOPT(int, VmciConnectTimeout, ZMQ_VMCI_CONNECT_TIMEOUT) // milliseconds +}; +//+------------------------------------------------------------------+ +//| The option value is a string with predefined byte length | +//| | +//| If it is a NULL-terminated string without predefined length, | +//| The situation is tricky: we do not know the length of the option | +//| value beforehand, but the function does not return the correct | +//| one, either. So the only option is to guess. | +//| | +//| Here we adopt the solution of the Java binding. We just guess | +//| that the length of a NULL-terminated string option is less than | +//| 1024. So hopefully, it is the case. | +//+------------------------------------------------------------------+ +bool SocketOptions::getStringOption(int option, string &value, size_t length) +{ + uchar buf[]; + ArrayResize(buf, (int)length); + bool res = getOption(option, buf, length); + if (res) + { + value = StringFromUtf8(buf); + } + ArrayFree(buf); + return res; +} +//+------------------------------------------------------------------+ +//| The ending means that the converted buffer contains the ending | +//| null. | +//+------------------------------------------------------------------+ +bool SocketOptions::setStringOption(int option, const string value, bool ending) +{ + uchar buf[]; + StringToUtf8(value, buf, ending); + int len = ArraySize(buf); + bool res = setOption(option, buf, len); + ArrayFree(buf); + return res; +} +//+------------------------------------------------------------------+ diff --git a/Documents/Resources/ZeroMQ/Includes/Z85.mqh b/Documents/Resources/ZeroMQ/Includes/Zmq/Z85.mqh similarity index 55% rename from Documents/Resources/ZeroMQ/Includes/Z85.mqh rename to Documents/Resources/ZeroMQ/Includes/Zmq/Z85.mqh index 08e1357..4563774 100644 --- a/Documents/Resources/ZeroMQ/Includes/Z85.mqh +++ b/Documents/Resources/ZeroMQ/Includes/Zmq/Z85.mqh @@ -24,130 +24,160 @@ #import "libzmq.dll" // Encode data with Z85 encoding. Returns 0(NULL) if failed -intptr_t zmq_z85_encode(char &str[],const uchar &data[],size_t size); +intptr_t zmq_z85_encode(char &str[], const uchar &data[], size_t size); // Decode data with Z85 encoding. Returns 0(NULL) if failed -intptr_t zmq_z85_decode(uchar &dest[],const char &str[]); +intptr_t zmq_z85_decode(uchar &dest[], const char &str[]); // Generate z85-encoded public and private keypair with tweetnacl/libsodium -int zmq_curve_keypair(char &z85_public_key[],char &z85_secret_key[]); +int zmq_curve_keypair(char &z85_public_key[], char &z85_secret_key[]); // Derive the z85-encoded public key from the z85-encoded secret key -int zmq_curve_public(char &z85_public_key[],const char &z85_secret_key[]); +int zmq_curve_public(char &z85_public_key[], const char &z85_secret_key[]); #import //+------------------------------------------------------------------+ //| Z85 encoding/decoding | //+------------------------------------------------------------------+ class Z85 - { +{ public: - static bool encode(string &secret,const uchar &data[]); - static bool decode(const string secret,uchar &data[]); + static bool encode(string &secret, const uchar &data[]); + static bool decode(const string secret, uchar &data[]); - static string encode(string data); - static string decode(string secret); + static string encode(string data); + static string decode(string secret); - static bool generateKeyPair(uchar &publicKey[],uchar &secretKey[]); - static bool derivePublic(uchar &publicKey[],const uchar &secretKey[]); + static bool generateKeyPair(uchar &publicKey[], uchar &secretKey[]); + static bool derivePublic(uchar &publicKey[], const uchar &secretKey[]); - static bool generateKeyPair(string &publicKey,string &secretKey); - static string derivePublic(const string secretKey); - }; + static bool generateKeyPair(string &publicKey, string &secretKey); + static string derivePublic(const string secretKey); +}; //+------------------------------------------------------------------+ //| data must have size multiple of 4 | //+------------------------------------------------------------------+ -bool Z85::encode(string &secret,const uchar &data[]) - { - int size=ArraySize(data); - if(size%4 != 0) return false; +bool Z85::encode(string &secret, const uchar &data[]) +{ + int size = ArraySize(data); + if (size % 4 != 0) + return false; - char str[]; - ArrayResize(str,(int)(1.25*size+1)); + char str[]; + ArrayResize(str, (int)(1.25 * size + 1)); - intptr_t res=zmq_z85_encode(str,data,size); - if(res == 0) return false; - secret = StringFromUtf8(str); - return true; - } + intptr_t res = zmq_z85_encode(str, data, size); + if (res == 0) + return false; + secret = StringFromUtf8(str); + return true; +} //+------------------------------------------------------------------+ //| secret must be multiples of 5 | //+------------------------------------------------------------------+ -bool Z85::decode(const string secret,uchar &data[]) - { - int len=StringLen(secret); - if(len%5 != 0) return false; +bool Z85::decode(const string secret, uchar &data[]) +{ + int len = StringLen(secret); + if (len % 5 != 0) + return false; - char str[]; - StringToUtf8(secret,str); - ArrayResize(data,(int)(0.8*len)); - return 0 != zmq_z85_decode(data,str); - } + char str[]; + StringToUtf8(secret, str); + ArrayResize(data, (int)(0.8 * len)); + return 0 != zmq_z85_decode(data, str); +} //+------------------------------------------------------------------+ //| data length should be multiples of 4 and only ascii is supported | //+------------------------------------------------------------------+ string Z85::encode(string data) - { - char str[]; - StringToUtf8(data,str,false); - string res; - if(encode(res,str)) - return res; - else - return ""; - } +{ + uchar str[]; + StringToUtf8(data, str, false); + string res; + if (encode(res, str)) + return res; + else + return ""; +} //+------------------------------------------------------------------+ //| secret must be multiples of 5 | //+------------------------------------------------------------------+ -string Z85::decode(string secret) - { - uchar data[]; - decode(secret,data); - return StringFromUtf8(data); - } +string Z85::decode(string secret) +{ + uchar data[]; + decode(secret, data); + return StringFromUtf8(data); +} //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ -bool Z85::generateKeyPair(uchar &publicKey[],uchar &secretKey[]) - { - ArrayResize(publicKey,41); - ArrayResize(secretKey,41); - return 0==zmq_curve_keypair(publicKey, secretKey); - } +bool Z85::generateKeyPair(uchar &publicKey[], uchar &secretKey[]) +{ + char pubKey[41], secKey[41]; + bool result = (0 == zmq_curve_keypair(pubKey, secKey)); + if (result) + { + ArrayResize(publicKey, 41); + ArrayResize(secretKey, 41); + for (int i = 0; i < 41; i++) + { + publicKey[i] = (uchar)pubKey[i]; + secretKey[i] = (uchar)secKey[i]; + } + } + return result; +} //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ -bool Z85::derivePublic(uchar &publicKey[],const uchar &secretKey[]) - { - ArrayResize(publicKey,41); - return 0==zmq_curve_public(publicKey, secretKey); - } +bool Z85::derivePublic(uchar &publicKey[], const uchar &secretKey[]) +{ + char pubKey[41]; + char secKey[41]; + // Convert uchar array to char array + int size = ArraySize(secretKey); + for (int i = 0; i < size && i < 41; i++) + { + secKey[i] = (char)secretKey[i]; + } + + bool result = (0 == zmq_curve_public(pubKey, secKey)); + if (result) + { + ArrayResize(publicKey, 41); + for (int i = 0; i < 41; i++) + { + publicKey[i] = (uchar)pubKey[i]; + } + } + return result; +} //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ -bool Z85::generateKeyPair(string &publicKey,string &secretKey) - { - uchar sec[],pub[]; - bool res=generateKeyPair(pub,sec); - if(res) - { - secretKey=StringFromUtf8(sec); - publicKey=StringFromUtf8(pub); - } - ArrayFree(sec); - ArrayFree(pub); - return res; - } +bool Z85::generateKeyPair(string &publicKey, string &secretKey) +{ + uchar sec[], pub[]; + bool res = generateKeyPair(pub, sec); + if (res) + { + secretKey = StringFromUtf8(sec); + publicKey = StringFromUtf8(pub); + } + ArrayFree(sec); + ArrayFree(pub); + return res; +} //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ string Z85::derivePublic(const string secrect) - { - uchar sec[],pub[]; - StringToUtf8(secrect,sec); - derivePublic(pub,sec); - string pubstr=StringFromUtf8(pub); - ArrayFree(sec); - ArrayFree(pub); - return pubstr; - } +{ + uchar sec[], pub[]; + StringToUtf8(secrect, sec); + derivePublic(pub, sec); + string pubstr = StringFromUtf8(pub); + ArrayFree(sec); + ArrayFree(pub); + return pubstr; +} //+------------------------------------------------------------------+ diff --git a/Documents/Resources/ZeroMQ/Includes/Zmq/Zmq.mqh b/Documents/Resources/ZeroMQ/Includes/Zmq/Zmq.mqh new file mode 100644 index 0000000..cfaa9af --- /dev/null +++ b/Documents/Resources/ZeroMQ/Includes/Zmq/Zmq.mqh @@ -0,0 +1,98 @@ +//+------------------------------------------------------------------+ +//| Module: Zmq.mqh | +//| This file is part of the mql-zmq project: | +//| https://github.com/dingmaotu/mql-zmq | +//| | +//| Copyright 2016-2017 Li Ding | +//| | +//| Licensed under the Apache License, Version 2.0 (the "License"); | +//| you may not use this file except in compliance with the License. | +//| You may obtain a copy of the License at | +//| | +//| http://www.apache.org/licenses/LICENSE-2.0 | +//| | +//| Unless required by applicable law or agreed to in writing, | +//| software distributed under the License is distributed on an | +//| "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, | +//| either express or implied. | +//| See the License for the specific language governing permissions | +//| and limitations under the License. | +//+------------------------------------------------------------------+ +#property strict + +#include +#include "AtomicCounter.mqh" +#include "Z85.mqh" +#include "Socket.mqh" +//+------------------------------------------------------------------+ +//| Definitions from zmq.h | +//+------------------------------------------------------------------+ +#define ZMQ_VERSION_MAJOR 4 +#define ZMQ_VERSION_MINOR 2 +#define ZMQ_VERSION_PATCH 0 + +#define ZMQ_HAS_CAPABILITIES 1 + +#import "libzmq.dll" +// Error code +int zmq_errno(void); +// Resolves system errors and 0MQ errors to human-readable string +intptr_t zmq_strerror(int errnum); +// Run-time API version detection +void zmq_version(int &major, int &minor, int &patch); +// Probe library capabilities +int zmq_has(const char &capability[]); +#import +//+------------------------------------------------------------------+ +//| ZMQ global utilities | +//+------------------------------------------------------------------+ +class Zmq +{ +protected: + static bool has(string cap); + +public: + //--- Capabilities + static bool hasIpc() { return has("ipc"); } // ipc - the library supports the ipc:// protocol + static bool hasPgm() { return has("pgm"); } // pgm - the library supports the pgm:// protocol + static bool hasTipc() { return has("tipc"); }; // tipc - the library supports the tipc:// protocol + static bool hasNorm() { return has("norm"); }; // norm - the library supports the norm:// protocol + static bool hasCurve() { return has("curve"); }; // curve-the library supports the CURVE security mechanism + static bool hasGssApi() { return has("gssapi"); }; // gssapi-the library supports the GSSAPI security mechanism + + //--- Error handling + static int errorNumber() { return zmq_errno(); } + static string errorMessage(int error = 0); + + //--- Version + static string getVersion(); +}; +//+------------------------------------------------------------------+ +//| Wrap zmq_has | +//+------------------------------------------------------------------+ +bool Zmq::has(string cap) +{ + char capstr[]; + StringToUtf8(cap, capstr); + bool res = (ZMQ_HAS_CAPABILITIES == zmq_has(capstr)); + ArrayFree(capstr); + return res; +} +//+------------------------------------------------------------------+ +//| Wraps zmq_strerror | +//+------------------------------------------------------------------+ +string Zmq::errorMessage(int error) +{ + intptr_t ref = error > 0 ? zmq_strerror(error) : zmq_strerror(zmq_errno()); + return StringFromUtf8Pointer(ref); +} +//+------------------------------------------------------------------+ +//| Get version string of current zmq | +//+------------------------------------------------------------------+ +string Zmq::getVersion(void) +{ + int major, minor, patch; + zmq_version(major, minor, patch); + return StringFormat("%d.%d.%d", major, minor, patch); +} +//+------------------------------------------------------------------+ diff --git a/Documents/Resources/ZeroMQ/Includes/ZmqMsg.mqh b/Documents/Resources/ZeroMQ/Includes/Zmq/ZmqMsg.mqh similarity index 56% rename from Documents/Resources/ZeroMQ/Includes/ZmqMsg.mqh rename to Documents/Resources/ZeroMQ/Includes/Zmq/ZmqMsg.mqh index a7a69bd..b30ef8c 100644 --- a/Documents/Resources/ZeroMQ/Includes/ZmqMsg.mqh +++ b/Documents/Resources/ZeroMQ/Includes/Zmq/ZmqMsg.mqh @@ -30,123 +30,150 @@ // hopefully MetaQuotes do malloc structs // aligned on pointer address boundaries struct zmq_msg_t - { - uchar _[64]; - }; +{ + uchar _[64]; +}; #import "libzmq.dll" int zmq_msg_init(zmq_msg_t &msg); -int zmq_msg_init_size(zmq_msg_t &msg,size_t size); -// As mt4 can not provide a zmq_free_fn, and can not let +int zmq_msg_init_size(zmq_msg_t &msg, size_t size); +// As mt4 can not provide a zmq_free_fn, and can not let // zmq library own the array data, copying is always needed. // Therefore this function will not be used by this binding. // int zmq_msg_init_data(zmq_msg_t &msg,uchar &data[], // int size,int ffn,int hint); int zmq_msg_close(zmq_msg_t &msg); -int zmq_msg_move(zmq_msg_t &dest,zmq_msg_t &src); -int zmq_msg_copy(zmq_msg_t &dest,zmq_msg_t &src); +int zmq_msg_move(zmq_msg_t &dest, zmq_msg_t &src); +int zmq_msg_copy(zmq_msg_t &dest, zmq_msg_t &src); // char * intptr_t zmq_msg_data(zmq_msg_t &msg); int zmq_msg_size(zmq_msg_t &msg); int zmq_msg_more(zmq_msg_t &msg); -int zmq_msg_get(zmq_msg_t &msg,int property); -int zmq_msg_set(zmq_msg_t &msg,int property,int optval); +int zmq_msg_get(zmq_msg_t &msg, int property); +int zmq_msg_set(zmq_msg_t &msg, int property, int optval); // const char * -intptr_t zmq_msg_gets(zmq_msg_t &msg,const char &property[]); +intptr_t zmq_msg_gets(zmq_msg_t &msg, const char &property[]); #import //+------------------------------------------------------------------+ //| Wraps a zmq_msg_t | //+------------------------------------------------------------------+ -struct ZmqMsg: public zmq_msg_t - { +struct ZmqMsg : public zmq_msg_t +{ protected: - int get(int property) {return zmq_msg_get(this,property);} - bool set(int property,int value) {return 0==zmq_msg_set(this,property,value);} - intptr_t data() {return zmq_msg_data(this);} - bool setStringData(string data,bool nullterminated=false); + int get(int property) { return zmq_msg_get(this, property); } + bool set(int property, int value) { return 0 == zmq_msg_set(this, property, value); } + intptr_t data() { return zmq_msg_data(this); } + bool setStringData(string data, bool nullterminated = false); + public: - ZmqMsg() {zmq_msg_init(this);} - ZmqMsg(int size) {if(0!=zmq_msg_init_size(this,size)){Debug("Failed to init size msg: insufficient space");}} - ZmqMsg(string data,bool nullterminated=false) {setStringData(data,nullterminated);} - ~ZmqMsg() {if(0!=zmq_msg_close(this)){Debug("Failed to close msg");}} + ZmqMsg() { zmq_msg_init(this); } + ZmqMsg(int size) + { + if (0 != zmq_msg_init_size(this, size)) + { + Debug("Failed to init size msg: insufficient space"); + } + } + ZmqMsg(string data, bool nullterminated = false) { setStringData(data, nullterminated); } + ~ZmqMsg() + { + if (0 != zmq_msg_close(this)) + { + Debug("Failed to close msg"); + } + } - bool rebuild() - { - if(0!=zmq_msg_close(this)){Debug("Failed to close msg");return false;} - return 0==zmq_msg_init(this); - } - bool rebuild(int size) - { - if(0!=zmq_msg_close(this)){Debug("Failed to close msg");return false;} - return 0==zmq_msg_init_size(this,size); - } - bool rebuild(string data,bool nullterminated=false) - { - if(0!=zmq_msg_close(this)){Debug("Failed to close msg");return false;} - return setStringData(data,nullterminated); - } + bool rebuild() + { + if (0 != zmq_msg_close(this)) + { + Debug("Failed to close msg"); + return false; + } + return 0 == zmq_msg_init(this); + } + bool rebuild(int size) + { + if (0 != zmq_msg_close(this)) + { + Debug("Failed to close msg"); + return false; + } + return 0 == zmq_msg_init_size(this, size); + } + bool rebuild(string data, bool nullterminated = false) + { + if (0 != zmq_msg_close(this)) + { + Debug("Failed to close msg"); + return false; + } + return setStringData(data, nullterminated); + } - size_t size() {return zmq_msg_size(this);} + size_t size() { return zmq_msg_size(this); } - void getData(uchar &bytes[]); - string getData(); - void setData(const uchar &bytes[]); + void getData(uchar &bytes[]); + string getData(); + void setData(const uchar &bytes[]); - bool more() {return 1==zmq_msg_more(this);} + bool more() { return 1 == zmq_msg_more(this); } - bool copy(ZmqMsg &msg) {return 0 == zmq_msg_copy(this, msg);} - bool move(ZmqMsg &msg) {return 0 == zmq_msg_move(this, msg);} + bool copy(ZmqMsg &msg) { return 0 == zmq_msg_copy(this, msg); } + bool move(ZmqMsg &msg) { return 0 == zmq_msg_move(this, msg); } - string meta(const string property); - }; + string meta(const string property); +}; //+------------------------------------------------------------------+ //| Initialize a utf-8 string message | //+------------------------------------------------------------------+ -bool ZmqMsg::setStringData(string data,bool nullterminated) - { - uchar array[]; - StringToUtf8(data,array,nullterminated); - bool res=(0==zmq_msg_init_size(this,ArraySize(array))); - if(res)setData(array); - return res; - } +bool ZmqMsg::setStringData(string data, bool nullterminated) +{ + uchar array[]; + StringToUtf8(data, array, nullterminated); + bool res = (0 == zmq_msg_init_size(this, ArraySize(array))); + if (res) + setData(array); + return res; +} //+------------------------------------------------------------------+ //| Get message data as bytes array | //+------------------------------------------------------------------+ void ZmqMsg::getData(uchar &bytes[]) - { - size_t size=size(); - intptr_t src=data(); - if(ArraySize(bytes)