-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathWOApplication.swift
More file actions
691 lines (590 loc) · 21.7 KB
/
Copy pathWOApplication.swift
File metadata and controls
691 lines (590 loc) · 21.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
//
// WOApplication.swift
// SwiftObjects
//
// Created by Helge Hess on 11.05.18.
// Copyright © 2018-2026 ZeeZide. All rights reserved.
//
import struct Foundation.Data
import struct Foundation.Date
import struct Foundation.TimeInterval
import class Foundation.UserDefaults
import Synchronization
/**
* This is the main entry class for Go web applications. You usually
* start writing a Go app by subclassing this class. It then provides all
* the setup of the Go infrastructure (creation of session and resource
* managers, handling of initial requests, etc etc)
*
* The default name for the subclass is 'Application', alongside 'Context'
* for a WOContext subclass and 'Session' for the app specific WOSession
* subclass.
*
* A typical thing one might want to setup in an Application subclass is a
* connection to the database.
*
* When you host within Jetty, this is a typical main() function for a Go based
* web application:
*
* public static void main(String[] args) {
* new WOJettyRunner(PackBack.class, args).run();
* }
*
* - FIXME: document it way more.
* - FIXME: document how it works in a Servlet environment
* - FIXME: document how properties are located and loaded
*
* ### Differences to WebObjects
*
* FIXME: document all the diffs ;-)
*
* #### QuerySession
*
* In addition to Context and Session subclasses, Go has the concept of a
* 'QuerySession'. The baseclass is WOQuerySession and an application can
* subclass this.
* FIXME: document more
*
* #### Zope like Object Publishing
*
* FIXME: document all this. Class registry, product manager, root object,
* renderer factory.
*
* Request handler processing can be turned on and off.
*
* #### pageWithName()
*
* In Go this supports component specific resource managers, not just the
* global one. The WOApplication pageWithName takes this into account, it
* is NOT the fallback root lookup (and thus can be used in all contexts).
* It first checks the active WOComponent for the resource manager.
*/
open class WOApplication : WOLifecycle, WOResponder, WORequestDispatcher,
GoObjectRendererFactory, KeyValueCodingType,
SmartDescription
{
public let log : WOLogger = WOPrintLogger(logLevel: .Log)
let properties = UserDefaults.standard
let requestCounter = Atomic<Int>(0)
let activeDispatchCount = Atomic<Int>(0)
open var contextClass : WOContext.Type? = nil
open var sessionClass : WOSession.Type? = nil
open var querySessionClass : WOQuerySession.Type = WOQuerySession.self
var requestHandlerRegistry = [ String : WORequestHandler ]()
open var defaultRequestHandler : WORequestHandler?
var _name : String? = nil
open var name : String {
set { _name = newValue }
get { return _name ?? UObject.getSimpleName(self) }
}
/**
* The session store of the application.
*
* *Important!*: Only call this method in properly locked sections, the
* sessionStore ivar is not protected.
*
* Usually you should only call this in the applications init() method or
* constructor.
*/
open var sessionStore : WOSessionStore
// TBD: I think this configures how 'expires' is set
open var isPageRefreshOnBacktrackEnabled : Bool = true
/**
* Can be overridden by subclasses to configure whether an application should
* refuse to accept new session (e.g. when its in shutdown mode).
* The method always returns false in the default implementation.
*/
open var refusesNewSessions : Bool { return false }
open var defaultSessionTimeOut : TimeInterval {
let t = UserDefaults.standard.integer(forKey: "WOSessionTimeOut")
return TimeInterval(t > 0 ? t : 3600)
}
open var resourceManager : WOResourceManager? = nil {
didSet {
guard let rm = resourceManager else { return }
if sessionClass == nil {
sessionClass = rm.lookupClass("Session") as? WOSession.Type
}
if contextClass == nil {
contextClass = rm.lookupClass("Context") as? WOContext.Type
}
}
}
public init() {
self.sessionStore = WOServerSessionStore()
// TODO: setup resourceManager
registerInitialRequestHandlers()
}
/**
* This method registers the default request handlers, that is:
*
* - WODirectActionRequestHandler ('wa' and 'x')
* - WOResourceRequestHandler ('wr', 'WebServerResources', 'Resources')
* - WOComponentRequestHandler ('wo')
*/
func registerInitialRequestHandlers() {
let da = WODirectActionRequestHandler(application: self)
registerRequestHandler(da, for: directActionRequestHandlerKey)
registerRequestHandler(da, for: "x")
defaultRequestHandler = da
let ra = WOResourceRequestHandler(application: self)
registerRequestHandler(ra, for: resourceRequestHandlerKey)
registerRequestHandler(ra, for: "WebServerResources")
registerRequestHandler(ra, for: "Resources")
let ca = WOComponentRequestHandler(application: self)
registerRequestHandler(ca, for: componentRequestHandlerKey)
}
// MARK: - Lifecycle
/**
* This method is called by handleRequest() when the application starts to
* process a given request. Since it has no WOContext parameter its rather
* useless :-)
*/
open func awake() {
}
/**
* The balancing method to awake(). Called at the end of the handleRequest().
*/
open func sleep() {
}
// MARK: - Main Request Entry Point
lazy var favicon : Data? = {
return resourceManager?.dataForResourceNamed("favicon.ico", languages: [])
}()
open func dispatchRequest(_ request: WORequest) -> WOResponse {
requestCounter.wrappingAdd(1, ordering: .relaxed)
activeDispatchCount.wrappingAdd(1, ordering: .relaxed)
defer { activeDispatchCount.wrappingAdd(-1, ordering: .relaxed) }
// TODO: port CORS stuff, OPTIONS
guard let rh = requestHandler(for: request) else {
log.error("Missing request handler for request:", request)
let r = WOResponse(request: request)
r.status = 500
try? r.appendContentHTMLString("Missing request handler!")
return r
}
var response : WOResponse?
do {
response = try rh.handleRequest(request)
}
catch {
log.error("Failed to generate response:", error)
let r = WOResponse(request: request)
r.status = 500
try? r.appendContentHTMLString("Error during response generation.")
response = r
}
if response == nil && request.uri == "/favicon.ico", let data = favicon {
let r = WOResponse(request: request)
r.setHeader("image/x-icon", for: "Content-Type")
r.contents = data
response = r
}
guard let finalResponse = response else {
// e.g. favicon.ico
log.trace("Got no response to request:", request)
let r = WOResponse(request: request)
r.status = 500
try? r.appendContentHTMLString("Could not generate response.")
return r
}
// TODO: add CORS headers
return finalResponse
}
open func createContext(for request: WORequest) -> WOContext {
return (contextClass ?? WOAppContext.self)
.init(application: self, request: request)
}
// MARK: - Request Handlers
/**
* Returns the WORequestHandler which is responsible for the given request.
* This retrieves the request handler key from the request. If there is none,
* or if the key maps to nothing the `defaultRequestHandler()` is
* used.
* Otherwise the WORequestHandler stored for the key will be returned.
*
* @param _rq - the WORequest to be handled
* @return a WORequestHandler object responsible for processing the request
*/
open func requestHandler(for request: WORequest) -> WORequestHandler? {
if request.uri == "/favicon.ico" {
if let rh = requestHandlerRegistry[resourceRequestHandlerKey] {
return rh
}
}
guard let key = request.requestHandlerKey,
let rh = requestHandlerRegistry[key] else
{
return defaultRequestHandler
}
return rh
}
open func registerRequestHandler(_ rh: WORequestHandler, for key: String) {
requestHandlerRegistry[key] = rh
}
open var registeredRequestHandlerKeys : [ String ] {
return Array(requestHandlerRegistry.keys)
}
open var directActionRequestHandlerKey : String {
return properties.string(forKey: "WODirectActionRequestHandlerKey") ?? "wa"
}
open var componentRequestHandlerKey : String {
return properties.string(forKey: "WOComponentRequestHandlerKey") ?? "wo"
}
open var resourceRequestHandlerKey : String {
return properties.string(forKey: "WOResourceRequestHandlerKey") ?? "wr"
}
// MARK: - Errors
open func handleError(_ error: Swift.Error, in context: WOContext)
-> WOActionResults?
{
// TODO: special thing for GoSecurityException
do {
return try renderObject(error, in: context)
}
catch {
log.error("Error while rendering error:", error)
return nil
}
}
open func handleSessionRestorationError(in context: WOContext)
-> WOActionResults?
{
let r = context.application.redirectToApplicationEntry(in: context)
let u = r?.header(for: "Location") ?? ("/" + context.application.name)
let myResponse = WOResponse(request: context.request)
try? myResponse.appendContentString(
"""
<h2>Could not restore session!</h2>
<p>
Return to application entry point:
<a href="\(u)">\(context.application.name.htmlEscaped)</a>
</p>
"""
)
return myResponse
}
open func handlePageRestorationError(in context: WOContext)
-> WOResponse
{
// long time, no see :-)
context.response.status = 500 // TBD
try? context.response
.appendContentString("<h1>You have backtracked too far</h1>!")
return context.response
}
open func handleMissingAction(_ action: String, in context: WOContext)
-> WOActionResults?
{
try? context.response.appendContentHTMLString("Missing action: \(action)!")
return context.response
}
// MARK: - Rendering Results
/**
* This methods determines the renderer for the given object in the given
* context.
*
* - if the object is null, we return null
* - if the object is a GoSecurityException, we check whether the
* authenticator of the exceptions acts as a IGoObjectRendererFactory.
* If this returns a result, it is used as the renderer.
* - next, if there is a context the
* IGoObjectRendererFactory.Utility.rendererForObjectInContext()
* function is called in an attempt to locate a renderer by traversing
* the path, looking for a IGoObjectRendererFactory which can return
* a result.
* - then, the products are checked for appropriate renderers, by
* invoking the rendererForObjectInContext() of the product manager.
* - and finally the GoDefaultRenderer will get used (if it can process
* the object)
*
* @param _o - the object which shall be rendered
* @param _ctx - the context in which the rendering should happen
* @return a renderer object (a GoObjectRenderer)
*/
open func rendererForObject(_ object: Any?, in context: WOContext)
-> GoObjectRenderer?
{
// TODO: the security stuff
// TODO: Go traversal path lookup
// TODO: product support
if GoDefaultRenderer.shared.canRenderObject(object, in: context) {
return GoDefaultRenderer.shared
}
return nil
}
/**
* Renders the given object in the given context. It does so by looking up
* a 'renderer' object (a GoObjectRenderer) using
* rendererForObjectInContext() and then calling renderObjectInContext()
* on it.
*
* In the default configuration this will usually use the GoDefaultRenderer
* which can deal with quite a few setups.
*
* @param _result - the object to be rendered
* @param _ctx - the context in which the rendering should happen
* @return a WOResponse containing the rendered results
*/
open func renderObject(_ object: Any?,
in context: WOContext) throws -> WOResponse?
{
guard let renderer = rendererForObject(object, in: context) else {
log.error("did not find renderer for object:", object,
"type:", type(of: object))
let r = context.response
r.status = 500
try? r.appendContentHTMLString("did not find renderer for object")
return r
}
do {
try renderer.renderObject(object, in: context)
}
catch {
do {
return try renderObject(error, in: context)
}
catch {
return nil
}
}
return context.response
}
/**
* This method is called by the GoDefaultRenderer if its asked to render a
* WOApplication object. This usually means that the root-URL of the
* application was accessed.
* The default implementation will return a redirect to the `wa/Main/default`
* GoPath.
*
* @param _ctx - the WOContext the request happened in
* @return a WOResponse to be used for the application object
*/
open func redirectToApplicationEntry(in context: WOContext) -> WOResponse? {
let drh = defaultRequestHandler
let rm = resourceManager
let url : String
if drh is WODirectActionRequestHandler, let rm = rm,
rm.lookupDirectActionClass("DirectAction") != nil
{
url = "DirectAction/default"
}
else if let rm = rm, rm.lookupComponentClass("Main") != nil {
url = "Main/default"
}
else {
log.error("Did not find DirectAction or Main for initial request")
return nil
}
var qd = [ String : Any? ]()
for ( name, values ) in context.request.formValues {
qd[name] = values
}
if context.hasSession {
qd[WORequest.SessionIDKey] = context.session.sessionID
}
else {
qd.removeValue(forKey: WORequest.SessionIDKey)
}
let fullURL = context.directActionURLForActionNamed(url, with: qd)
let response = WOResponse(request: context.request)
response.status = 302 // Found
response.setHeader(fullURL, for: "Location")
return response
}
// MARK: - Responder
/**
* This starts the takeValues phase of the request processing. In this phase
* the relevant objects fill themselves with the state of the request before
* the action is invoked.
*
* The default method calls the takeValuesFromRequest() of the WOSession, if
* one is active. Otherwise it enters the contexts' page and calls
* takeValuesFromRequest() on it.
*/
open func takeValues(from request: WORequest, in context: WOContext) throws {
if context.hasSession {
try context.session.takeValues(from: request, in: context)
}
else if let page = context.page {
context.enterComponent(page)
defer { context.leaveComponent(page) }
try page.takeValues(from: request, in: context)
}
}
/**
* This triggers the invokeAction phase of the request processing. In this
* phase the relevant objects got their form values pushed in and the action
* is ready to be performed.
*
* The default method calls the invokeAction() of the WOSession, if
* one is active. Otherwise it enters the contexts' page and calls
* invokeAction() on it.
*/
open func invokeAction(for request : WORequest,
in context : WOContext) throws -> Any?
{
if context.hasSession {
return try context.session.invokeAction(for: request, in: context)
}
else if let page = context.page {
context.enterComponent(page)
defer { context.leaveComponent(page) }
return try page.invokeAction(for: request, in: context)
}
else {
return nil
}
}
/**
* Render the page stored in the WOContext. This works by calling
* appendToResponse() on the WOSession, if there is one. If there is none,
* the page set in the context will get invoked directly.
*
* @param _response - the response
* @param _ctx - the context
*/
open func append(to response: WOResponse, in context: WOContext) throws {
if context.hasSession {
try context.session.append(to: response, in: context)
}
else if let page = context.page {
context.enterComponent(page)
defer { context.leaveComponent(page) }
try page.append(to: response, in: context)
}
}
// MARK: - Sessions
/**
* Uses the configured WOSessionStore to unarchive a WOSession for the current
* request(/context).
* All code should use this method instead of directly dealing with the
* session store.
*
* Note: this method also checks out the session from the store to avoid
* concurrent modifications!
*/
open func restoreSession(with id: String, in ctx: WOContext) -> WOSession? {
let session = sessionStore.checkOutSession(for: id, from: ctx.request)
// TODO: scan cookies, port (if session == nil)
if let session = session {
ctx.session = session
session.awake(in: ctx)
}
return session
}
/**
* Save the session to a store and check it in.
*/
open func saveSession(of context: WOContext) -> Bool {
guard context.hasSession else { return false }
context.session.sleep(in: context)
sessionStore.checkInSession(of: context)
return true
}
/**
* This is called by WORequest or our handleRequest() in case a session needs
* to be created. It calls createSessionForRequest() to instantiate the clean
* session object. It then registers the session in the context and performs
* wake up (calls awakeWithContext()).
*
* @param _ctx the context in which the session shall be active initially.
* @return a fresh session
*/
open func initializeSession(in context: WOContext) -> WOSession? {
guard let session = createSession(for: context.request) else { return nil }
session.timeout = defaultSessionTimeOut
context.setNewSession(session)
session.awake(in: context)
return session
}
/**
* Called by initializeSession to create a new session for the given request.
*
* This method is a hook for subclasses which want to change the class of
* the WOSession object based on the request. If they just want to change the
* static class, they can change the 'sessionClass' ivar.
*
* @param _rq the request which is associated with the new session.
* @return a new, not-yet-awake session
*/
open func createSession(for request: WORequest) -> WOSession? {
return (sessionClass ?? WOSession.self).init()
}
/**
* This method gets called by WOContext if its asked to restore a query
* session. If you want to store complex objects in your session, you might
* want to override this.
*/
open func restoreQuerySession(in context: WOCoreContext) -> WOQuerySession {
return WOQuerySession(context: context)
}
// MARK: - Page Handling
/**
* Primary method for user code to generate new WOComponent objects. This is
* also called by WOComponent.pageWithName().
*
* The method first locates a WOResourceManager by asking the active
* component, and if this has none, it uses the WOResourceManager set in the
* application.
* It then asks the WOResourceManager to instantiate the page. Afterwards it
* awakes the component in the given WOContext.
*
* Again: do not trigger the WOResourceManager directly, always use this
* method (or WOComponent.pageWithName()) to acquire WOComponents.
*
* @param _pageName - the name of the WOComponent to instantiate
* @param _ctx - the context for the component
* @return the WOComponent or null if the WOResourceManager found none
*/
open func pageWithName(_ name: String, in context: WOContext) -> WOComponent?
{
guard let rm = context.component?.resourceManager ?? resourceManager else {
log.error("Did not find resource manager to instantiate page:", name)
return nil
}
guard let page = rm.pageWithName(name, in: context) else {
log.error("Did not instantiate page:", name, "using:", rm)
return nil
}
page.ensureAwake(in: context)
return page
}
// MARK: - KVC
open func value(forKey k: String) -> Any? {
// Handle computed properties not found by typeInfo
switch k {
case "name": return name
case "registeredRequestHandlerKeys": return registeredRequestHandlerKeys
case "directActionRequestHandlerKey": return directActionRequestHandlerKey
case "componentRequestHandlerKey": return componentRequestHandlerKey
case "resourceRequestHandlerKey": return resourceRequestHandlerKey
case "refusesNewSessions": return refusesNewSessions
case "defaultSessionTimeOut": return defaultSessionTimeOut
default: break
}
return defaultValueForKey(k)
}
// MARK: - Description
open func appendToDescription(_ ms: inout String) {
if let s = _name { ms += " '\(s)'" }
ms += " #req=\(requestCounter.load(ordering: .relaxed))"
ms += "/\(activeDispatchCount.load(ordering: .relaxed))"
ms += " rh=\(requestHandlerRegistry.keys.joined(separator:","))"
if refusesNewSessions { ms += " REFUSES-NEW" }
ms += " timeout=\(defaultSessionTimeOut)s"
if let rh = defaultRequestHandler { ms += " def=\(rh)" }
else { ms += " no-default-rh" }
if let rm = resourceManager { ms += " rm=\(rm)" }
else { ms += " no-rm?" }
}
}
public protocol WORequestDispatcher {
// This is a main reason why the WO API would need to be adjusted for modern,
// async, processing. But then, people are still using RoR! ;-)
func dispatchRequest(_ request: WORequest) -> WOResponse
}
public protocol WOLifecycle {
func awake()
func sleep()
}