@jsm-mit/rabbit-motoko-package 0.1.37 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,7 @@
1
1
  type Task =
2
2
  record {
3
3
  channel: text;
4
+ commonId: text;
4
5
  completedAt: int;
5
6
  createdAt: int;
6
7
  expiresAt: int;
@@ -12,6 +13,39 @@ type Task =
12
13
  timesOutAt: int;
13
14
  worker: principal;
14
15
  };
16
+ type Result_4 =
17
+ variant {
18
+ err: Error;
19
+ ok: bool;
20
+ };
21
+ type Result_3 =
22
+ variant {
23
+ err: Error;
24
+ ok: vec nat;
25
+ };
26
+ type Result_2 =
27
+ variant {
28
+ err: Error;
29
+ ok: Task;
30
+ };
31
+ type Result_1 =
32
+ variant {
33
+ err: Error;
34
+ ok: vec Task;
35
+ };
36
+ type Result =
37
+ variant {
38
+ err: Error;
39
+ ok: nat;
40
+ };
41
+ type Error =
42
+ variant {
43
+ AlreadyExists;
44
+ InvalidData: text;
45
+ NotAuthorized: text;
46
+ NotFound;
47
+ ReturnsNull;
48
+ };
15
49
  type CompleteTaskArgs =
16
50
  record {
17
51
  id: nat;
@@ -25,16 +59,23 @@ type ClaimTaskArgs =
25
59
  type AddTaskArgs =
26
60
  record {
27
61
  channel: text;
62
+ commonId: text;
28
63
  parentIds: opt vec nat;
29
64
  payload: text;
30
65
  };
31
66
  service : {
32
- addTask: (args: AddTaskArgs) -> (nat);
33
- claimTask: (args: ClaimTaskArgs) -> (opt Task);
34
- completeTask: (args: CompleteTaskArgs) -> (bool);
35
- getAvailableTaskIds: (channel: text) -> (vec nat) query;
36
- getTask: (id: nat) -> (opt Task) query;
37
- getTasks: () -> (vec Task) query;
38
- getTasksLast24h: () -> (vec Task) query;
67
+ addTask: (args: AddTaskArgs) -> (Result);
68
+ claimTask: (args: ClaimTaskArgs) -> (Result_2);
69
+ completeTask: (args: CompleteTaskArgs) -> (Result_4);
70
+ getAvailableTaskIds: (channel: text) -> (Result_3) query;
71
+ getTask: (id: nat) -> (Result_2) query;
72
+ getTasks: () -> (Result_1) query;
73
+ getTasksByChannelAndCommonId: (channel: text, commonId: text) ->
74
+ (Result_1) query;
75
+ getTasksByCommonId: (commonId: text) -> (Result_1) query;
76
+ getTasksLast24h: () -> (Result_1) query;
77
+ testErrWithText: () -> (Result) query;
78
+ testErrWithText2: () -> (Result) query;
79
+ testError: () -> (Result) query;
39
80
  whoAmI: () -> (principal) query;
40
81
  }
@@ -4,11 +4,27 @@ import type { IDL } from '@icp-sdk/core/candid';
4
4
 
5
5
  export interface AddTaskArgs {
6
6
  'parentIds' : [] | [Array<bigint>],
7
+ 'commonId' : string,
7
8
  'channel' : string,
8
9
  'payload' : string,
9
10
  }
10
11
  export interface ClaimTaskArgs { 'id' : bigint, 'timeoutNanos' : bigint }
11
12
  export interface CompleteTaskArgs { 'id' : bigint, 'message' : string }
13
+ export type Error = { 'NotFound' : null } |
14
+ { 'NotAuthorized' : string } |
15
+ { 'InvalidData' : string } |
16
+ { 'AlreadyExists' : null } |
17
+ { 'ReturnsNull' : null };
18
+ export type Result = { 'ok' : bigint } |
19
+ { 'err' : Error };
20
+ export type Result_1 = { 'ok' : Array<Task> } |
21
+ { 'err' : Error };
22
+ export type Result_2 = { 'ok' : Task } |
23
+ { 'err' : Error };
24
+ export type Result_3 = { 'ok' : Array<bigint> } |
25
+ { 'err' : Error };
26
+ export type Result_4 = { 'ok' : boolean } |
27
+ { 'err' : Error };
12
28
  export interface Task {
13
29
  'id' : bigint,
14
30
  'status' : bigint,
@@ -18,18 +34,24 @@ export interface Task {
18
34
  'timesOutAt' : bigint,
19
35
  'createdAt' : bigint,
20
36
  'parentIds' : [] | [Array<bigint>],
37
+ 'commonId' : string,
21
38
  'worker' : Principal,
22
39
  'channel' : string,
23
40
  'payload' : string,
24
41
  }
25
42
  export interface _SERVICE {
26
- 'addTask' : ActorMethod<[AddTaskArgs], bigint>,
27
- 'claimTask' : ActorMethod<[ClaimTaskArgs], [] | [Task]>,
28
- 'completeTask' : ActorMethod<[CompleteTaskArgs], boolean>,
29
- 'getAvailableTaskIds' : ActorMethod<[string], Array<bigint>>,
30
- 'getTask' : ActorMethod<[bigint], [] | [Task]>,
31
- 'getTasks' : ActorMethod<[], Array<Task>>,
32
- 'getTasksLast24h' : ActorMethod<[], Array<Task>>,
43
+ 'addTask' : ActorMethod<[AddTaskArgs], Result>,
44
+ 'claimTask' : ActorMethod<[ClaimTaskArgs], Result_2>,
45
+ 'completeTask' : ActorMethod<[CompleteTaskArgs], Result_4>,
46
+ 'getAvailableTaskIds' : ActorMethod<[string], Result_3>,
47
+ 'getTask' : ActorMethod<[bigint], Result_2>,
48
+ 'getTasks' : ActorMethod<[], Result_1>,
49
+ 'getTasksByChannelAndCommonId' : ActorMethod<[string, string], Result_1>,
50
+ 'getTasksByCommonId' : ActorMethod<[string], Result_1>,
51
+ 'getTasksLast24h' : ActorMethod<[], Result_1>,
52
+ 'testErrWithText' : ActorMethod<[], Result>,
53
+ 'testErrWithText2' : ActorMethod<[], Result>,
54
+ 'testError' : ActorMethod<[], Result>,
33
55
  'whoAmI' : ActorMethod<[], Principal>,
34
56
  }
35
57
  export declare const idlFactory: IDL.InterfaceFactory;
@@ -1,9 +1,18 @@
1
1
  export const idlFactory = ({ IDL }) => {
2
2
  const AddTaskArgs = IDL.Record({
3
3
  'parentIds' : IDL.Opt(IDL.Vec(IDL.Nat)),
4
+ 'commonId' : IDL.Text,
4
5
  'channel' : IDL.Text,
5
6
  'payload' : IDL.Text,
6
7
  });
8
+ const Error = IDL.Variant({
9
+ 'NotFound' : IDL.Null,
10
+ 'NotAuthorized' : IDL.Text,
11
+ 'InvalidData' : IDL.Text,
12
+ 'AlreadyExists' : IDL.Null,
13
+ 'ReturnsNull' : IDL.Null,
14
+ });
15
+ const Result = IDL.Variant({ 'ok' : IDL.Nat, 'err' : Error });
7
16
  const ClaimTaskArgs = IDL.Record({
8
17
  'id' : IDL.Nat,
9
18
  'timeoutNanos' : IDL.Int,
@@ -17,19 +26,33 @@ export const idlFactory = ({ IDL }) => {
17
26
  'timesOutAt' : IDL.Int,
18
27
  'createdAt' : IDL.Int,
19
28
  'parentIds' : IDL.Opt(IDL.Vec(IDL.Nat)),
29
+ 'commonId' : IDL.Text,
20
30
  'worker' : IDL.Principal,
21
31
  'channel' : IDL.Text,
22
32
  'payload' : IDL.Text,
23
33
  });
34
+ const Result_2 = IDL.Variant({ 'ok' : Task, 'err' : Error });
24
35
  const CompleteTaskArgs = IDL.Record({ 'id' : IDL.Nat, 'message' : IDL.Text });
36
+ const Result_4 = IDL.Variant({ 'ok' : IDL.Bool, 'err' : Error });
37
+ const Result_3 = IDL.Variant({ 'ok' : IDL.Vec(IDL.Nat), 'err' : Error });
38
+ const Result_1 = IDL.Variant({ 'ok' : IDL.Vec(Task), 'err' : Error });
25
39
  return IDL.Service({
26
- 'addTask' : IDL.Func([AddTaskArgs], [IDL.Nat], []),
27
- 'claimTask' : IDL.Func([ClaimTaskArgs], [IDL.Opt(Task)], []),
28
- 'completeTask' : IDL.Func([CompleteTaskArgs], [IDL.Bool], []),
29
- 'getAvailableTaskIds' : IDL.Func([IDL.Text], [IDL.Vec(IDL.Nat)], ['query']),
30
- 'getTask' : IDL.Func([IDL.Nat], [IDL.Opt(Task)], ['query']),
31
- 'getTasks' : IDL.Func([], [IDL.Vec(Task)], ['query']),
32
- 'getTasksLast24h' : IDL.Func([], [IDL.Vec(Task)], ['query']),
40
+ 'addTask' : IDL.Func([AddTaskArgs], [Result], []),
41
+ 'claimTask' : IDL.Func([ClaimTaskArgs], [Result_2], []),
42
+ 'completeTask' : IDL.Func([CompleteTaskArgs], [Result_4], []),
43
+ 'getAvailableTaskIds' : IDL.Func([IDL.Text], [Result_3], ['query']),
44
+ 'getTask' : IDL.Func([IDL.Nat], [Result_2], ['query']),
45
+ 'getTasks' : IDL.Func([], [Result_1], ['query']),
46
+ 'getTasksByChannelAndCommonId' : IDL.Func(
47
+ [IDL.Text, IDL.Text],
48
+ [Result_1],
49
+ ['query'],
50
+ ),
51
+ 'getTasksByCommonId' : IDL.Func([IDL.Text], [Result_1], ['query']),
52
+ 'getTasksLast24h' : IDL.Func([], [Result_1], ['query']),
53
+ 'testErrWithText' : IDL.Func([], [Result], ['query']),
54
+ 'testErrWithText2' : IDL.Func([], [Result], ['query']),
55
+ 'testError' : IDL.Func([], [Result], ['query']),
33
56
  'whoAmI' : IDL.Func([], [IDL.Principal], ['query']),
34
57
  });
35
58
  };
@@ -5,32 +5,29 @@ export declare class RabbitMotokoActor {
5
5
  private readonly host;
6
6
  private actor;
7
7
  private agent;
8
- private lastSyncTime;
9
8
  constructor(canisterId: string, identity?: Secp256k1KeyIdentity);
10
9
  private initActor;
11
10
  private setupAgent;
12
- private runFunctionSafely;
11
+ private runFunctionAndSyncTimeIfNecessaryAsyncUnsafe;
12
+ private handleResultErrors;
13
13
  syncTimeAsync(throwError: boolean): Promise<void>;
14
+ testErrWithText(): Promise<import("../declarations/rabbit-motoko-backend/rabbit-motoko-backend.did.js").Result>;
15
+ testError(): Promise<import("../declarations/rabbit-motoko-backend/rabbit-motoko-backend.did.js").Result>;
14
16
  /**
15
17
  * Adds a new task to the queue.
16
18
  */
17
- addTaskAsync(args: AddTaskArgs, throwError: boolean): Promise<bigint>;
19
+ addTaskAsync(args: AddTaskArgs, throwException: boolean): Promise<bigint | null>;
18
20
  /**
19
21
  * Claims a task for a specific worker.
20
22
  */
21
- claimTaskAsync(args: ClaimTaskArgs, throwError: boolean): Promise<[] | [Task]>;
23
+ claimTaskAsync(args: ClaimTaskArgs, throwException: boolean): Promise<Task | null>;
22
24
  /**
23
25
  * Completes a previously claimed task.
24
26
  */
25
- completeTaskAsync(args: CompleteTaskArgs, throwError: boolean): Promise<boolean>;
27
+ completeTaskAsync(args: CompleteTaskArgs, throwException: boolean): Promise<boolean>;
26
28
  /**
27
29
  * Fetches IDs of tasks available in a specific channel.
28
30
  */
29
- getAvailableTaskIdsAsync(channel: string, throwError: boolean): Promise<bigint[]>;
30
- /**
31
- * Returns a list of all tasks.
32
- */
33
- getTasksAsync(throwError: boolean): Promise<Task[]>;
34
- whoAmIAsync(throwError: boolean): Promise<string>;
31
+ getAvailableTaskIdsAsync(channel: string, throwException: boolean): Promise<bigint[]>;
35
32
  }
36
33
  //# sourceMappingURL=rabbit-motoko-actor.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"rabbit-motoko-actor.d.ts","sourceRoot":"","sources":["../src/rabbit-motoko-actor.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,oBAAoB,EAAE,MAAM,kCAAkC,CAAC;AAExE,OAAO,KAAK,EAAY,WAAW,EAAE,aAAa,EAAE,gBAAgB,EAAE,IAAI,EAAE,MAAM,oEAAoE,CAAC;AAGvJ,qBAAa,iBAAiB;IAMd,OAAO,CAAC,QAAQ,CAAC,UAAU;IALvC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAA6B;IAClD,OAAO,CAAC,KAAK,CAA2B;IACxC,OAAO,CAAC,KAAK,CAAY;IACzB,OAAO,CAAC,YAAY,CAAa;gBAEJ,UAAU,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,oBAAoB;IAehF,OAAO,CAAC,SAAS;YAOH,UAAU;YAYV,iBAAiB;IAiClB,aAAa,CAAC,UAAU,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAc9D;;OAEG;IACU,YAAY,CAAC,IAAI,EAAE,WAAW,EAAE,UAAU,EAAE,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC;IASlF;;OAEG;IACU,cAAc,CAAC,IAAI,EAAE,aAAa,EAAE,UAAU,EAAE,OAAO,GAAG,OAAO,CAAC,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;IAS3F;;OAEG;IACU,iBAAiB,CAAC,IAAI,EAAE,gBAAgB,EAAE,UAAU,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;IAS7F;;OAEG;IACU,wBAAwB,CAAC,OAA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wBAAwB,CAAC,OAAO,EAAE,MAAM,EAAE,cAAc,EAAE,OAAO,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;CAuBrG"}
@@ -1,12 +1,12 @@
1
1
  import { Actor, HttpAgent } from "@icp-sdk/core/agent";
2
2
  import { Secp256k1KeyIdentity } from "@icp-sdk/core/identity/secp256k1";
3
3
  import { idlFactory } from "../declarations/rabbit-motoko-backend/index.js";
4
- import { BetterJSON } from "@jsm-mit/utils-package";
4
+ import { BetterJSON, logErrorLocallyAndPublishOnErrorSubject } from "@jsm-mit/utils-package";
5
+ import { pigeon } from "@jsm-mit/pigeon-package";
5
6
  export class RabbitMotokoActor {
6
7
  constructor(canisterId, identity) {
7
8
  this.canisterId = canisterId;
8
9
  this.host = "https://icp0.io";
9
- this.lastSyncTime = 0;
10
10
  // 1. Tworzymy agenta
11
11
  this.agent = HttpAgent.createSync({
12
12
  host: this.host,
@@ -28,14 +28,13 @@ export class RabbitMotokoActor {
28
28
  try {
29
29
  // Synchronizacja czasu z siecią IC - rozwiązuje błąd "certificate is still too far in the future"
30
30
  await this.agent.syncTime();
31
- this.lastSyncTime = Date.now();
32
31
  console.log("✅ Agent IC zsynchronizowany pomyślnie.");
33
32
  }
34
33
  catch (err) {
35
34
  console.error("❌ Błąd podczas konfiguracji Agenta:", err);
36
35
  }
37
36
  }
38
- async runFunctionSafely(fn, throwError) {
37
+ async runFunctionAndSyncTimeIfNecessaryAsyncUnsafe(fn) {
39
38
  try {
40
39
  return fn();
41
40
  }
@@ -49,27 +48,25 @@ export class RabbitMotokoActor {
49
48
  }
50
49
  catch (err) {
51
50
  console.error(BetterJSON.stringify(err));
52
- if (throwError) {
53
- throw err;
54
- }
55
- else {
56
- return {};
57
- }
51
+ throw err;
58
52
  }
59
53
  }
60
54
  console.error(BetterJSON.stringify(error));
61
- if (throwError) {
62
- throw error;
63
- }
64
- else {
65
- return {};
66
- }
55
+ throw error;
67
56
  }
68
57
  }
58
+ handleResultErrors(functionName, params, error) {
59
+ pigeon.debugEmailAsyncSafe("debug", functionName, params, BetterJSON.stringify(error));
60
+ const errorKey = Object.keys(error)[0];
61
+ const errorMessage = error[errorKey];
62
+ return {
63
+ errorKey,
64
+ errorMessage
65
+ };
66
+ }
69
67
  async syncTimeAsync(throwError) {
70
68
  try {
71
69
  await this.agent.syncTime();
72
- this.lastSyncTime = Date.now();
73
70
  console.log("🔄 Czas agenta został zsynchronizowany ponownie.");
74
71
  }
75
72
  catch (err) {
@@ -79,70 +76,110 @@ export class RabbitMotokoActor {
79
76
  }
80
77
  }
81
78
  }
79
+ async testErrWithText() {
80
+ return this.actor.testErrWithText();
81
+ }
82
+ async testError() {
83
+ return this.actor.testError();
84
+ }
82
85
  /**
83
86
  * Adds a new task to the queue.
84
87
  */
85
- async addTaskAsync(args, throwError) {
88
+ async addTaskAsync(args, throwException) {
89
+ const errorMessage = "Network error: add task failed";
86
90
  try {
87
- return this.runFunctionSafely(() => this.actor.addTask(args), throwError);
91
+ const result = await this.runFunctionAndSyncTimeIfNecessaryAsyncUnsafe(() => this.actor.addTask(args));
92
+ if ('ok' in result) {
93
+ return result.ok;
94
+ }
95
+ else {
96
+ this.handleResultErrors("addTaskAsync", [args, throwException], result.err);
97
+ return null;
98
+ }
88
99
  }
89
- catch {
90
- throw new Error("Failed to add task");
100
+ catch (err) {
101
+ logErrorLocallyAndPublishOnErrorSubject(errorMessage, err);
102
+ if (throwException) {
103
+ throw err;
104
+ }
105
+ else {
106
+ return null;
107
+ }
91
108
  }
92
109
  }
93
110
  /**
94
111
  * Claims a task for a specific worker.
95
112
  */
96
- async claimTaskAsync(args, throwError) {
113
+ async claimTaskAsync(args, throwException) {
114
+ const errorMessage = "Network error: claim task failed";
97
115
  try {
98
- return this.runFunctionSafely(() => this.actor.claimTask(args), throwError);
116
+ const result = await this.runFunctionAndSyncTimeIfNecessaryAsyncUnsafe(() => this.actor.claimTask(args));
117
+ if ('ok' in result) {
118
+ return result.ok;
119
+ }
120
+ else {
121
+ this.handleResultErrors("claimTaskAsync", [args, throwException], result.err);
122
+ return null;
123
+ }
99
124
  }
100
- catch {
101
- throw new Error("Failed to claim task");
125
+ catch (err) {
126
+ logErrorLocallyAndPublishOnErrorSubject(errorMessage, err);
127
+ if (throwException) {
128
+ throw err;
129
+ }
130
+ else {
131
+ return null;
132
+ }
102
133
  }
103
134
  }
104
135
  /**
105
136
  * Completes a previously claimed task.
106
137
  */
107
- async completeTaskAsync(args, throwError) {
138
+ async completeTaskAsync(args, throwException) {
139
+ const errorMessage = "Network error: complete task failed";
108
140
  try {
109
- return this.runFunctionSafely(() => this.actor.completeTask(args), throwError);
141
+ const result = await this.runFunctionAndSyncTimeIfNecessaryAsyncUnsafe(() => this.actor.completeTask(args));
142
+ if ('ok' in result) {
143
+ return result.ok;
144
+ }
145
+ else {
146
+ this.handleResultErrors("completeTaskAsync", [args, throwException], result.err);
147
+ return false;
148
+ }
110
149
  }
111
- catch {
112
- throw new Error("Failed to complete task");
150
+ catch (err) {
151
+ logErrorLocallyAndPublishOnErrorSubject(errorMessage, err);
152
+ if (throwException) {
153
+ throw err;
154
+ }
155
+ else {
156
+ return false;
157
+ }
113
158
  }
114
159
  }
115
160
  /**
116
161
  * Fetches IDs of tasks available in a specific channel.
117
162
  */
118
- async getAvailableTaskIdsAsync(channel, throwError) {
119
- try {
120
- return this.runFunctionSafely(() => this.actor.getAvailableTaskIds(channel), throwError);
121
- }
122
- catch {
123
- throw new Error("Failed to get available task IDs");
124
- }
125
- }
126
- /**
127
- * Returns a list of all tasks.
128
- */
129
- async getTasksAsync(throwError) {
163
+ async getAvailableTaskIdsAsync(channel, throwException) {
164
+ const errorMessage = "Network error: get available task IDs failed";
130
165
  try {
131
- return this.runFunctionSafely(() => this.actor.getTasks(), throwError);
132
- }
133
- catch {
134
- throw new Error("Failed to get tasks");
135
- }
136
- }
137
- async whoAmIAsync(throwError) {
138
- try {
139
- return this.runFunctionSafely(() => {
140
- const result = this.actor.whoAmI();
141
- return Promise.resolve(result.toString());
142
- }, throwError);
166
+ const result = await this.runFunctionAndSyncTimeIfNecessaryAsyncUnsafe(() => this.actor.getAvailableTaskIds(channel));
167
+ if ('ok' in result) {
168
+ return result.ok;
169
+ }
170
+ else {
171
+ this.handleResultErrors("getAvailableTaskIdsAsync", [channel, throwException], result.err);
172
+ return [];
173
+ }
143
174
  }
144
- catch {
145
- throw new Error("Failed to get who I am");
175
+ catch (err) {
176
+ logErrorLocallyAndPublishOnErrorSubject(errorMessage, err);
177
+ if (throwException) {
178
+ throw err;
179
+ }
180
+ else {
181
+ return [];
182
+ }
146
183
  }
147
184
  }
148
185
  }
@@ -1,20 +1,15 @@
1
1
  import { Observable } from 'rxjs';
2
2
  import { RabbitMotokoActor, type Task } from '@jsm-mit/rabbit-motoko-package';
3
- import { Pigeon } from '@jsm-mit/pigeon-package';
4
3
  export declare class RabbitTaskWorker {
5
4
  private channel;
6
5
  private intervalMiliseconds;
7
6
  private actor;
8
- private pigeon;
9
7
  private intervalId;
10
8
  private isProcessing;
11
9
  private readonly taskSubject;
12
10
  get tasks$(): Observable<Task>;
13
- constructor(channel: string, intervalMiliseconds: number, actor: RabbitMotokoActor, pigeon: Pigeon);
14
- private claimAndProcessTask;
11
+ constructor(channel: string, intervalMiliseconds: number, actor: RabbitMotokoActor);
15
12
  private processQueue;
16
- completeTaskAsyncSafe(taskId: bigint): Promise<void>;
17
- addTaskAsyncSafe(channel: string, payload: string): Promise<void>;
18
13
  run(): void;
19
14
  stop(): void;
20
15
  }
@@ -1 +1 @@
1
- {"version":3,"file":"rabbit-task-worker.d.ts","sourceRoot":"","sources":["../src/rabbit-task-worker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAW,MAAM,MAAM,CAAC;AAC3C,OAAO,EAAE,iBAAiB,EAAsB,KAAK,IAAI,EAAE,MAAM,gCAAgC,CAAC;AAClG,OAAO,EAAE,MAAM,EAAE,MAAM,yBAAyB,CAAC;AAGjD,qBAAa,gBAAgB;IAUrB,OAAO,CA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52 @@
1
1
  import { Observable, Subject } from 'rxjs';
2
2
  import { RabbitMotokoActor } from '@jsm-mit/rabbit-motoko-package';
3
- import { Pigeon } from '@jsm-mit/pigeon-package';
4
- import { BetterJSON, handleErrorProperly } from '@jsm-mit/utils-package';
3
+ import { BetterJSON, logErrorLocallyAndPublishOnErrorSubject } from '@jsm-mit/utils-package';
5
4
  export class RabbitTaskWorker {
6
5
  get tasks$() {
7
6
  return this.taskSubject.asObservable();
8
7
  }
9
- constructor(channel, intervalMiliseconds, actor, pigeon) {
8
+ constructor(channel, intervalMiliseconds, actor) {
10
9
  this.channel = channel;
11
10
  this.intervalMiliseconds = intervalMiliseconds;
12
11
  this.actor = actor;
13
- this.pigeon = pigeon;
14
12
  this.intervalId = null;
15
13
  this.isProcessing = false;
16
14
  this.taskSubject = new Subject();
17
15
  }
18
- async claimAndProcessTask(args) {
19
- const claimResult = await this.actor.claimTaskAsync(args, true);
20
- if (claimResult.length > 0) {
21
- const task = claimResult[0] || {};
22
- console.log(`✅ Przejęto zadanie ${task.id}`);
23
- this.taskSubject.next(task);
24
- }
25
- }
26
16
  async processQueue() {
27
17
  if (this.isProcessing)
28
18
  return; // Zapobiega nakładaniu się wywołań
29
19
  this.isProcessing = true;
30
- try {
31
- const availableIds = await this.actor.getAvailableTaskIdsAsync(this.channel, true);
32
- if (!availableIds || availableIds.length === 0) {
33
- return;
34
- }
35
- const timeoutNanos = BigInt(5 * 60 * 1000000000);
36
- for (const taskId of availableIds) {
37
- const args = {
38
- id: taskId,
39
- timeoutNanos: timeoutNanos
40
- };
41
- try {
42
- await this.claimAndProcessTask(args);
43
- }
44
- catch (err) {
45
- // second attempt to claim after short delay, in case that time sync fixed the issue
46
- setTimeout(async () => {
47
- try {
48
- await this.claimAndProcessTask(args);
49
- }
50
- catch (claimErr) {
51
- this.pigeon.reportUrgentAsyncSafe('Error at claiming task', BetterJSON.stringify(claimErr));
52
- handleErrorProperly(`Error processing task ${taskId}`, claimErr);
53
- }
54
- }, 10 * 1000);
55
- }
56
- }
57
- }
58
- catch (error) {
59
- handleErrorProperly("Fatal error in TaskWorker", error);
60
- }
61
- finally {
62
- this.isProcessing = false;
63
- }
64
- }
65
- async completeTaskAsyncSafe(taskId) {
66
- try {
67
- await this.actor.completeTaskAsync({ id: taskId, message: "Zadanie ukończone przez RabbitTaskWorker" }, true);
68
- console.log(`✅ Zadanie ${taskId} oznaczone jako ukończone.`);
69
- }
70
- catch (err) {
71
- handleErrorProperly(`Błąd podczas completeTask (ID: ${taskId})`, err);
72
- }
73
- }
74
- async addTaskAsyncSafe(channel, payload) {
75
- try {
76
- await this.actor.addTaskAsync({ channel, payload, parentIds: [] }, true);
77
- console.log(`✅ Dodano nowe zadanie do kanału ${channel}.`);
78
- }
79
- catch (err) {
80
- handleErrorProperly(`Błąd podczas addTask (Kanał: ${channel})`, err);
81
- }
20
+ // try {
21
+ // const availableIds = await this.actor.getAvailableTaskIdsAsync(this.channel, true);
22
+ // if (!availableIds || availableIds.length === 0) {
23
+ // return;
24
+ // }
25
+ // const timeoutNanos = BigInt(5 * 60 * 1_000_000_000);
26
+ // for (const taskId of availableIds) {
27
+ // const args: ClaimTaskArgs = {
28
+ // id: taskId,
29
+ // timeoutNanos: timeoutNanos
30
+ // };
31
+ // try {
32
+ // await this.claimAndProcessTask(args);
33
+ // } catch (err) {
34
+ // // second attempt to claim after short delay, in case that time sync fixed the issue
35
+ // setTimeout(async () => {
36
+ // try {
37
+ // await this.claimAndProcessTask(args);
38
+ // } catch (claimErr) {
39
+ // this.pigeon.reportUrgentAsyncSafe('Error at claiming task', BetterJSON.stringify(claimErr));
40
+ // handleErrorProperly(`Error processing task ${taskId}`, claimErr);
41
+ // }
42
+ // }, 10 * 1000);
43
+ // }
44
+ // }
45
+ // } catch (error: any) {
46
+ // logErrorLocallyAndPublishOnErrorSubject("Error in processQueue", error);
47
+ // } finally {
48
+ // this.isProcessing = false;
49
+ // }
82
50
  }
83
51
  run() {
84
52
  if (this.intervalId)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jsm-mit/rabbit-motoko-package",
3
- "version": "0.1.37",
3
+ "version": "0.2.1",
4
4
  "description": "Wrapper TypeScript package for Rabbit Motoko Canister.",
5
5
  "license": "ISC",
6
6
  "author": "",
@@ -22,11 +22,18 @@
22
22
  "clean": "rm -rf dist",
23
23
  "prepare": "npm run build",
24
24
  "publish-public": "npm login && npm publish --access public",
25
- "test": "echo \"Error: no test specified\" && exit 1"
25
+ "test": "vitest",
26
+ "sandbox": "npx tsx sandbox/main.ts"
26
27
  },
27
28
  "peerDependencies": {
28
- "@jsm-mit/pigeon-package": "^0.1.0",
29
- "@jsm-mit/utils-package": "^0.1.0",
30
- "@icp-sdk/core": "^5.2.0"
29
+ "@icp-sdk/core": "^5.2.0",
30
+ "@jsm-mit/pigeon-package": "^0.5.0",
31
+ "@jsm-mit/utils-package": "^0.2.2"
32
+ },
33
+ "devDependencies": {
34
+ "@types/node": "^25.5.2",
35
+ "dotenv": "^16.3.1",
36
+ "tsx": "^4.18.0",
37
+ "vitest": "^1.0.0"
31
38
  }
32
- }
39
+ }